简体   繁体   中英

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.

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

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM