1

While using an async.series based design, I have to use a loop within a function block as shown below:

var someFile = filePath;
async.series([
    function(cb) {
         _.forEach (
               someDataList,
               function (item) {
                   //call that executes out of sync
                   writeToFile(someFile,item)
                   //how to provide callback here
                   cb(); //<- is this correct - won't this take control out of this block in the very first loop iteration?
               }
         );
    }
],
//callback function
function (err) {...}
);
1
  • you need to complete the loop and go to the next function? Commented Jan 9, 2018 at 10:52

2 Answers 2

2

You can use forEachSeries instead.

var someFile = filePath;
async.forEachSeries(someDataList, function(item, cb) {
   writeToFile(someFile, item)
   cb();
},
//callback function
function () {...}
);

Updated after comment:

Unfortunately there is no way of getting index of iteratee in forEachSeries. if you want index of iteratee, you can use eachOfSeries

var someFile = filePath;
async.eachOfSeries(someDataList, function(value, key, callback) {
    //Do something with key
    writeToFile(someFile, item)
    callback();
}, //callback function
function () {...}
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - could you also please let me know how to obtain the index of the iteratee within forEachSeries - I looked up online but couldn't find a clear example
2

To explore more about async, you can use their method each.

Applies the function iteratee to each item in coll, in parallel. The iteratee is called with an item from the list, and a callback for when it has finished. If the iteratee passes an error to its callback, the main callback (for the each function) is immediately called with the error.

Your code can be transformed to this:

var someFile = filePath;
async.series([
    function (cb) {
      async.each(someDataList, function (item, callback) {
        //call that executes out of sync
        writeToFile(someFile,item)

        // Execute internal callback for `async.each`
        callback()
      }, function (error) {
        if (error) {
          cb(error)
        } else {
          cb()
        }
      })
    }
  ],
//callback function
  function (err) {...
  }
);

But, of course, you need to take a look at your writeToFile function. If it is sync you need to wrap it in try {} catch(e){} construction and run internal callback() with error callback(error) in catch section.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.