0

为 Ajax 请求实现队列管理器。我决定采用这种方法而不是使用 Promise,因为我可以通过检查私有变量队列来访问排队的状态。此外,所需的代码要小一些。

这是一个非常特殊的情况,其中所有 ajax 请求都是并行触发的,但我想保证它们响应的顺序。

4

2 回答 2

1

我想我现在得到了你想要的。看看这个:

function AsyncQueue() {
    var results = {},
        queue = [];
    this.add = [].push.bind(queue); // add one token
    this.complete = function(token) {
        results[token] = arguments;
        while (queue[0] in results) {
             var t = queue.shift();
             this.resolve.apply(null, results[t]);
             delete results[t];
        }
    };
}
AsyncQueue.prototype.resolve = function() {
    console.log.apply(console, ["no resolver for"].concat([].slice.call(arguments)));
};

用法:

var manager = new AsyncQueue();
manager.resolve = function(token, res) {
    // do whatever you need to do here
    console.log(res);
};
manager.add(1, 2);
manager.complete(2, "second"); // logs nothing yet
manager.complete(1, "first"); // logs "first", then "second"
于 2013-04-01T16:08:35.860 回答
0

用例:

发送 ajax 调用时,请执行以下操作:

add(token)

在回调中接收 ajax 时,请执行以下操作:

complete(token, text);

管理队列

// queue snapshot
// [0] token1 - waiting - null
// [1] token2 - blocked - text
// token contains info/meta about the response_text
// item 1 is blocked waiting on item 0 to complete

var Queue = (function (){
        var queue = [],
            publik = {},
            len = 0;
        publik.add = function(token) {
            var temp = {};
                temp.token = token;
                temp.waiting = true;
                temp.text = null;
            len = queue.push(temp);
        };
        publik.complete = function(token, text) {
            var kindex,
                length;

            // should never come here
            // complete is always called after add
            if(len === 0) {
                return;
            }

            // simplest case, nothing is blocked
            if(len === 1) {
                return true;
            }

            // queued items waiting
            if(len > 1) {
                return true;
            }

            for(kindex = 0, length = queue.length; kindex < length; kindex++) {
                if(queue[kindex].waiting === true) {
                    // resolve the ones waiting.
                }
            }

            // queue the text

            // resolve previous

            // 
        };
        return pulbik;
    }());
于 2013-04-01T15:32:35.873 回答