我正在使用async.forEach来遍历数组并执行一些任务。一个代码段如下。
var docs = [1, 2, 3, 4, 5], i = 0;
async.forEach(docs, function(doc, async_callback_each){
var _name = 'doc_each_' + (++i);
console.log(_name);
async_callback_each(null, _name);
//Pass in no error and current function name, expecting to be printed.
}, function(err, result) {
console.log('async_callback_each', err, result);
})
代码输出
doc_each_1
doc_each_2
doc_each_3
doc_each_4
doc_each_5
async_callback_each undefined undefined
我很高兴在调用回调之前处理所有数组元素,但请注意,我无法接收传入的_name。它最终为未定义。这是正常的还是我做错了什么?
答案 0 :(得分:2)
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.
Note, that since this function applies iterator to each item in parallel, there is no guarantee that the iterator functions will complete in order.
Arguments
arr - An array to iterate over.
iterator(item, callback) - A function to apply to each item in arr. The iterator is passed a callback(err) which must be called once it has completed. If no error has occurred, the callback should be run without arguments or with an explicit null argument.
callback(err) - A callback which is called when all iterator functions have finished, or an error occurs.