Node.js /使用参数异步(Node.js / async each with parameter)

7 IT屋

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?

解决方案

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
    }
});

如文档中所述,关于 async.each



每个(arr,迭代器,回调)


将函数迭代器并行应用于arr中的每个项目。
迭代器将与列表中的一个项目一起调用,并在
完成时回调。如果迭代器将错误传递给其回调,则
主回调(针对每个函数)将立即以
错误进行调用。



我的函数将arr中的每个项目都作为参数。换句话说,我遍历了所有数组,并接受了该数组中的每个项目,并对这个项目的值应用了一个函数。


例如,


  arr = [" 0"," 1"," 2"," 3"] 
< / pre>

,我希望 async.each 会在此arr上进行迭代,并转换下一个循环:


  for(var i = 0; i  dosomething(arr [i]); 

到异步版本。


我该怎么做?


解决方案

您代码的异步版本为:



  async.each(arr,function(arrObj,callback){
dosomething(arrObj);
callback();
},function(err){
如果(err){
//发生错误
}否则{
//在.each被执行后执行其他操作
}
});

本文地址:IT屋 » Node.js /使用参数异步