问题
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.
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;
}
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
I tried using all()
method instead of then()
but it stopped execution after first chain. Am I missing something obvious?
Thanks for any advice.
Cheers
回答1:
Am I missing something obvious?
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');
});
来源:https://stackoverflow.com/questions/18933903/promise-chains-are-not-executed-sequentially-using-q-promise-library