Node.js / async each with parameter

2019-05-30 04:28发布

As written in the documentation, about async.each:

each(arr, iterator, callback)

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

My function get as param each of the items in the arr. In other words, I iterate over all the array, and I take each item in this array, and apply a function on the value of this item.

For example,

arr = ["0", "1", "2", "3"]

and I want that async.each will iterate on this arr, and convert the next loop:

for (var i=0; i<arr.length; i++)
    dosomething(arr[i]);

to async version.

How can I do it?

1条回答
forever°为你锁心
2楼-- · 2019-05-30 05:04

the async version for your code will be:

async.each(arr, function( arrObj, callback) {
    dosomething(arrObj);
    callback();
}, function(err){
    if( err ) {
      // do something with the error
    } else {
      //do something else after .each gets executed
    }
});
查看更多
登录 后发表回答