Search code examples
javascriptasynchronouses6-promise

Acting on Synchronous Promises


I have a few javascript functions that return promises. I'm using .then to act on the data returned from those functions. However, is the order guaranteed in the below code? Will result2 get processed after result?

const test = promiseReturningFunction(data);
test.then((result) => {
  doStuff(result);
});
const test2 = promiseReturningFunction2(data2);
test2.then((result2) => {
  doStuff(result2);
});

Or should this be rewritten along the lines of:

const test = promiseReturningFunction(data);
test.then((result) => {
  doStuff(result);
}).then(() => {
  const test2 = promiseReturningFunction2(data2);
  test2.then((result2) => {
    doStuff(result2);
  });
});

In short: is .then blocking?


Solution

  • No, the order of then callbacks on independent promises is not guaranteed. This is pretty much necessary to allow concurrent processing of multiple asynchronous tasks.

    If you need a particular order, you need to explicit chain your promise callbacks.

    In your case, if you just need the two doStuff calls to run after each other, but want to concurrently process the two promiseReturningFunctions, you can use

    const p1 = promiseReturningFunction(data);
    const p2 = test.then(doStuff);
    const p3 = promiseReturningFunction2(data2);
    Promise.all([p2, p3]).then((stuff, result2) => doStuff(result2));
    

    If you want to have the two promiseReturningFunctions run sequentially, then your second snippet is fine.