async.each(有效处理数据数组)

当我们想要处理数据数组时,最好使用 async.each 。当我们想要对所有数据执行某些操作并希望在完成所有操作后获得最终回调时,此方法将非常有用。这是以并行方式处理的。

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);
    //Returning callback is must. Else it wont get the final callback, even if we miss to return one callback
    createUser(eachUserName, callback);
  
}, function(err) {
    //If any of the user creation failed may throw error.
    if( err ) {
      // One of the iterations produced an error.
      // All processing will now stop.
      console.log('unable to create user');
    } else {
      console.log('All user created successfully');
    }
});

要一次执行一个可以使用 async.eachSeries