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