Home > front end >  Order of execution of back to back JavaScript Promises
Order of execution of back to back JavaScript Promises

Time:07-08

In the following code:

new Promise((resolve, reject) => {
    asyncFunc1(resolve,reject);
})
    .then((result) => {
        // do then1 stuff
    })
    
    
new Promise((resolve, reject) => {
    asyncFunc2(resolve,reject);
})
    .then((result) => {
        // do then2 stuff
    })

Will asyncFunc1()'s .then() complete before asyncFunc2() is executed?

Or will both execute (nearly) simultaneously, and their then()s execute just whenever they happen to return?

If the second one does not wait for the first one, is there a way to make it do so other than moving asyncFunc2() into asyncFunc1()'s .then()?

CodePudding user response:

Both promises will execute (nearly) simultaneously, because that is exactly one of the strengths of Javascript: Due to its callback-based design, it can kick off and wait for many asynchronous functions (in the form of promises) in parallel, without the need for the developer to care about complex handling of threads or anything like that.

If you want to have asyncFunc2 wait for the completion of asyncFunc1, it needs to be placed inside the then-block of asyncFunc1.

You can easily see and proof that by simulating two functions which take a defined time (using setTimeout), for example:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved at '   new Date().toISOString());
    }, 2000);
  });
}

function resolveAfter3Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved at '   new Date().toISOString());
    }, 3000);
  });
}

function execPromises() {
  console.log('calling at '    new Date().toISOString());
  resolveAfter2Seconds().then(result => console.log(result));
  resolveAfter3Seconds().then(result => console.log(result));
}

execPromises();

You will see in the console output that the first one will finish 2 sec after starting the script, the other one 3 sec after starting the script (and not after 2 3 = 5 sec).

If you want to make asyncFunc2 wait for asyncFunc1 without the need for then, you can use the async/await keywords.

In my example, the function execPromises would then look like this (asyncFunc2 executed after completion of asyncFunc1!):

async function execPromises() {
  console.log('calling at '    new Date().toISOString());
  const resultA = await resolveAfter2Seconds();
  console.log(resultA);
  const resultB = await resolveAfter3Seconds();
  console.log(resultB);
}
  • Related