async.each to handle an array of data efficiently

suggest change

When you want to handle an array of data, it's better to use async.each. It runs an operation for every item, in parallel, and invokes a final callback once every operation has finished.

function createUser(userName, callback)
{
    //create user in db
    callback(null)//or error based on creation
}

var arrayOfData = ['Ritu', 'Sid', 'Tom'];
async.each(arrayOfData, function(eachUserName, callback) {

    // Perform operation on each user.
    console.log('Creating user '+eachUserName);
    // You must call the iteratee callback. If one call is skipped, the final callback never runs.
    createUser(eachUserName, callback);
  
}, function(err) {
    // If any user creation failed, this receives the error.
    if( err ) {
      // One of the iterations produced an error.
      // The final callback is invoked with that error. Tasks already started may still finish.
      console.log('unable to create user');
    } else {
      console.log('All users created successfully');
    }
});

To process one item at a time, use async.eachSeries.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents