【发布时间】:2015-06-23 03:44:42
【问题描述】:
我努力完全把握承诺的下一部分......
我正在尝试创建一个简单的承诺队列(长期目标是限制数据库上的查询),然后我可以将其与 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.")})
【问题讨论】: