简单承诺队列:q.all 在延迟承诺解决之前解决

simple promise queue: q.all resolving before deferred promises resolve

我努力完全把握承诺的下一部分...

我正在尝试创建一个简单的承诺队列(长期目标是限制对数据库的查询),然后我可以将其与 Q.all() 和 Array.protoype.map() 一起使用。

(这似乎与this question有关,但我在那里没有看到明确的解决方案。)

这是我的简单框架:

var Q = require('q');

var queue = [];
var counter = 0;
var throttle = 2;  // i can do things at most two at a time

var addToQueue = function(data) {
    var deferred = Q.defer();
    queue.push({data: data, promise: deferred});
    processQueue();
    return(deferred.promise);
}

var processQueue = function() {
    if(queue.length > 0 && counter < throttle) {
       counter++;
       var item = queue.shift();
       setTimeout(function() {  // simulate long running async process
          console.log("Processed data item:" + item.data);
          item.promise.resolve();
          counter--;
          if(queue.length > 0 && counter < throttle) {
             processQueue(); // on to next item in queue
          }
       }, 1000);
    }
}

data = [1,2,3,4,5];
Q.all(data.map(addToQueue))
    .then(console.log("Why did get here before promises all fulfilled?"))
    .done(function() {
        console.log("Now we are really done with all the promises.");
    });

但是,正如上面所暗示的,"then" 会立即被调用,只有 "done" 被推迟到所有承诺的解决。我在 api documentation 中注意到唯一的示例确实使用了 .done() 而不是 then()。所以也许这是预期的行为?问题是我无法链接其他操作。在那种情况下,我需要创建另一个延迟承诺并在 Q.all 的 done 函数中解决它,如下所示

data = [1,2,3,4,5];

var deferred = Q.defer();

deferred.promise
    .then(function() {
        console.log("All data processed and chained function called.");
    })  // could chain additional actions here as needed.

Q.all(data.map(addToQueue))
    .done(function() {
        console.log("Now we are really done with all the promises.");
        deferred.resolve();
    });

这按预期工作,但额外的步骤让我觉得我一定遗漏了一些关于如何正确使用 Q.all() 的东西。

我对 Q.all() 的使用有问题吗,或者上面的额外步骤实际上是正确的方法吗?

编辑:

Tyrsius 指出我对 .then 的论点不是对函数的引用,而是立即计算函数 (console.log(...))。这是我应该如何做到的:

Q.all(data.map(addToQueue))
    .then(function() { console.log("Ahhh...deferred execution as expected.")})

实际上你的问题是标准 Javascript。

Q.all(data.map(addToQueue))
    .then(console.log("Why did get here before promises all fulfilled?"))
    .done(function() {
        console.log("Now we are really done with all the promises.");
    });

仔细看第二行。 Console.log 正在立即计算并作为参数发送到 .then。这与承诺无关,它只是 javascript 解析函数调用的方式。你需要这个

Q.all(data.map(addToQueue))
        .then(function() { console.log("Why did get here before promises all fulfilled?")})
        .done(function() {
            console.log("Now we are really done with all the promises.");
        });

编辑

如果这是你经常做的事情,你可以制作一个按你想要的方式工作的函数返回函数

function log(data) {
    return function() { console.log(data);}
}

Q.all(data.map(addToQueue))
        .then(log("Why did get here before promises all fulfilled?"))
        .done(function() {
            console.log("Now we are really done with all the promises.");
        });