2

async.memoize(), 这个函数中注释后的最后一个 else 块是做什么的?

https://github.com/caolan/async/blob/master/lib/async.js#L671

async.memoize = function (fn, hasher) {
    var memo = {};
    var queues = {};
    hasher = hasher || function (x) {
        return x;
    };
    var memoized = function () {
        var args = Array.prototype.slice.call(arguments);
        var callback = args.pop();
        var key = hasher.apply(null, args);
        if (key in memo) {
            callback.apply(null, memo[key]);
        }
        else if (key in queues) {
            queues[key].push(callback);
        }
        else {
            // what does this else block do?
            queues[key] = [callback];
            fn.apply(null, args.concat([function () {
                memo[key] = arguments;
                var q = queues[key];
                delete queues[key];
                for (var i = 0, l = q.length; i < l; i++) {
                  q[i].apply(null, arguments);
                }
            }]));
        }
    };
    memoized.unmemoized = fn;
    return memoized;
};
4

1 回答 1

1

If the key is not found in either the memo or the queues objects (the first two parts of the if statement), then it calls the callback and assigns the return value from the callback to queues[key] as a one element array.

Then, it calls whatever functions where in the queue[key] array.

于 2012-08-22T01:29:54.240 回答