async.js each get index in iterator
Update
Since writing this answer, there is now a better solution. Please see xuanji's answer for details
Original
Thanks to @genexp for a simple and concise example in the comments below...
async.each(someArray, function(item, done){
console.log(someArray.indexOf(item));
});
Having read the docs, I suspected that there wasn't any way to access an integer representing position in the list...
Applies an iterator function to each item in an array, 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 this callback, the main callback for the each function is immediately called with the error.
Note, that since this function applies the iterator to each item in parallel there is no guarantee that the iterator functions will complete in order.
So I dug a little deeper (Source code link)
async.each = function (arr, iterator, callback) {
callback = callback || function () {};
if (!arr.length) {
return callback();
}
var completed = 0;
_each(arr, function (x) {
iterator(x, only_once(function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
if (completed >= arr.length) {
callback(null);
}
}
}));
});
};
As you can see there's a completed
count which is updated as each callback completes but no actual index position.
Incidentally, there's no issue with race conditions on updating the completed
counter as JavaScript is purely single-threaded under the covers.
Edit: After digging further into the iterator, it looks like you might be able to reference an index
variable thanks to closures...
async.iterator = function (tasks) {
var makeCallback = function (index) {
var fn = function () {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
};
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
};
return makeCallback(0);
};
You can use async.forEachOf
- it calls its iterator callback with the index as its second argument.
> async.forEachOf(['a', 'b', 'c'], function () {console.log(arguments)});
{ '0': 'a', '1': 0, '2': [Function] }
{ '0': 'b', '1': 1, '2': [Function] }
{ '0': 'c', '1': 2, '2': [Function] }
see the docs for more info.