async.js each get index in iterator

后端 未结 6 1692
一整个雨季
一整个雨季 2021-02-02 07:04

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(elemen         


        
6条回答
  •  长情又很酷
    2021-02-02 07:57

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

提交回复
热议问题