Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h3>Update</h3> <p>Since writing this answer, there is now a better solution. Please see <a href="https://stackoverflow.com/a/31821896/156755">xuanji's answer</a> for details</p> <h3>Original</h3> <p><strong>Thanks to @genexp</strong> for a simple and concise example in the comments below...</p> <pre><code>async.each(someArray, function(item, done){ console.log(someArray.indexOf(item)); }); </code></pre> <hr> <p>Having read the docs, I suspected that there wasn't any way to access an integer representing position in the list...</p> <blockquote> <p>Applies an iterator function to each item in an array, <strong>in parallel</strong>. 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.</p> <p>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.</p> </blockquote> <p>So I dug a little deeper (<a href="https://github.com/caolan/async/blob/master/lib/async.js#L101-L121" rel="nofollow noreferrer">Source code link</a>) </p> <pre><code>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 &gt;= arr.length) { callback(null); } } })); }); }; </code></pre> <p>As you can see there's a <code>completed</code> count which is updated as each callback completes but no actual index position.</p> <p>Incidentally, there's no issue with race conditions on updating the <code>completed</code> counter as JavaScript is <a href="http://ejohn.org/blog/how-javascript-timers-work/" rel="nofollow noreferrer">purely single-threaded</a> under the covers.</p> <p><strong>Edit:</strong> After digging further into the iterator, it looks like you <em>might</em> be able to reference an <code>index</code> variable thanks to closures...</p> <pre><code>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 &lt; tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; }; return makeCallback(0); }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload