I'm using caolan's async.js library, specifically the .each method.
How do you get access to the index in the iterator?
async.each(ary, function(element, callback){
//do stuff here for each element in ary
//how do I get access to the index?
}, function(err) {
//final callback here
})
Just use
async.forEachOf()
.For detail, see documentation here.
The method
async.each()
will iterate the array in parallel, and it doesn't provide the element's index to the iterating callback.So when you have:
While you COULD use
Array.indexOf()
to find it:This requires an in-memory search in the array for EVERY iteration of the array. For large-ish arrays, this might slow everything down quite badly.
A better workaround could be by using
async.eachSeries()
instead, and keep track of the index yourself:With
eachSeries()
, you are guaranteed that things will be done in the right order.Another workaround, which is the async's maintainer's first choice, is to iterate with Object.keys:
I hope this helps.
You can use
async.forEachOf
- it calls its iterator callback with the index as its second argument.see the docs for more info.
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...
Having read the docs, I suspected that there wasn't any way to access an integer representing position in the list...
So I dug a little deeper (Source code link)
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...