使用Q promise库不会按顺序执行Promise链 [英] Promise chains are not executed sequentially using Q promise library
问题描述
我在代码中执行多个批处理异步操作。虽然批处理中的操作应该异步执行,但是批处理应该一个接一个地同步执行。
I am performing multiple batched asynchronous operations in my code. Although operations within a batch should execute asynchronously batches should be executed synchronously one after another.
这是一个 jsfiddle 我创建了。查看控制台,因为所有输出都在那里。以下是为方便起见的代码:
Here is a jsfiddle I created. Look at the console as all output is there. And here is the code for convenience:
asyncChain(10, 'FIRST CHAIN')
.then(function () {
asyncChain(10, 'SECOND CHAIN');
})
.then(function(){
asyncChain(10, 'THIRD CHAIN');
});
function asyncChain(n, msg) {
var promiseChain = Q.fcall(function () {
10;
});
console.log('starting:' + msg);
for (var i = 0; i < n; i++) {
promiseChain = promiseChain.then(asyncOperation(i, msg));
}
console.log('returning' + msg);
return promiseChain;
}
function asyncOperation(i, msg) {
var d = Q.defer();
setTimeout(function () {
console.log('resolving for #' + i + msg);
d.resolve(i);
}, 300 + Math.random()*1000);
return d.promise;
}
基本上这些是3批次的承诺操作我希望一个接一个地完成。这意味着此示例的输出将是这样的:
Basically these are 3 batched promise operations I expect to be finished one after another. Meaning the output for this sample would be something like this:
starting FIRST CHAIN
returning FIRST CHAIN
resolving 1..10 FIRST CHAIN
starting SECOND CHAIN
returning SECOND CHAIN
resolving 1..10 SECOND CHAIN
and so on
我尝试使用 all()
方法而不是然后()
但它在第一个链后停止执行。我错过了一些明显的东西吗
I tried using all()
method instead of then()
but it stopped execution after first chain. Am I missing something obvious?
感谢您的任何建议。
干杯
推荐答案
我错过了一些明显的东西吗?
Am I missing something obvious?
是的。对于然后
来解决与另一个承诺的承诺,您必须返回其他承诺。你的函数只是启动另一个 asyncChain
,但是从回调中返回 undefined
,它立即解析了这个承诺。
Yes. For then
to resolve the promise with another promise, you have to return that other promise to it. Your function does just start another asyncChain
, but returns undefined
from the callback which resolves the promise immediately.
asyncChain(10, 'FIRST CHAIN').then(function () {
return asyncChain(10, 'SECOND CHAIN');
}).then(function(){
return asyncChain(10, 'THIRD CHAIN');
});
这篇关于使用Q promise库不会按顺序执行Promise链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!