Noah Blues
Noah Blues

Reputation: 1359

What's the meaning the code block between line 169 and line 171 in async.js?

The code block is

if (completed >= arr.length) {
   return callback();
}

It is in the function _eachLimit.

My thought is that since JavaScript is single-threaded, the callback function which is in the parameter list of iterator function can be executed only once at a time, so situation that completed variable can not be modified by two callback function simultaneously. And if so, when callback function is called, it will check the completed variable every time so that it can end the while loop.

And the code block above seems like it is redundant, so what's the use of the code block?

Thanks a lot for answering my question.

The whole function is as below:

var _eachLimit = function (limit) {

    return function (arr, iterator, callback) {
        callback = callback || function () {};
        if (!arr.length || limit <= 0) {
            return callback();
        }
        var completed = 0;
        var started = 0;
        var running = 0;

        (function replenish () {
            if (completed >= arr.length) {
                return callback();
            }

            while (running < limit && started < arr.length) {
                started += 1;
                running += 1;
                iterator(arr[started - 1], function (err) {
                    if (err) {
                        callback(err);
                        callback = function () {};
                    }
                    else {
                        completed += 1;
                        running -= 1;
                        if (completed >= arr.length) {
                            callback();
                        }
                        else {
                            replenish();
                        }
                    }
                });
            }
        })();
    };
};

Upvotes: 1

Views: 164

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263137

From the code you posted, it seems you want to know why completed is checked against arr.length twice: both at the start of replenish() and from the callback function passed to iterator().

Javascript is indeed single-threaded (in browsers) (so far), but iterator() is asynchronous. It will return immediately and invoke the provided callback function some time later, and by that time completed and/or arr.length might have changed even though a single thread has run, so another check is indeed necessary.

Upvotes: 1

Related Questions