【问题标题】:ADT - Collapsbile queueADT - 可折叠队列
【发布时间】:2013-03-22 16:11:21
【问题描述】:

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

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

【问题讨论】:

  • 使用完成承诺 ;-) 不,说真的,我目前看不到您将如何使用此管理器 - 以及 complete 应该做什么。您在哪里/如何插入 ajax 函数,以及期望 ajax 结果的回调函数在哪里?

标签: javascript


【解决方案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"

【讨论】:

  • 我最终得到了一个有向无环图,并通过在 b.c.这很简单。最后我使用了我所谓的可折叠队列来实现。如果您对可折叠队列感兴趣,请告诉我,我会将其放在 git hub 上。
  • 这个问题太本地化了,所以我投票关闭它。
【解决方案2】:

用例:

发送 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;
    }());

【讨论】:

  • 那些resolve the ones waiting; queue the text; resolve previous cmets 好像有点不完整……
  • 我认为与其发布其他答案,不如更新以前的不完整答案。
猜你喜欢
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
相关资源
最近更新 更多