async memoized - 理解源代码

时间:2012-08-22 01:14:06

标签: javascript memoization async.js

async.memoize()开始,此函数中的注释之后的最后一个阻塞是什么?

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

1 个答案:

答案 0 :(得分:1)

如果在keymemo对象(queues语句的前两部分)中找不到if,则它会调用回调并且将回调值作为单元素数组分配给queues[key]

然后,它调用queue[key]数组中的任何函数。