Why do JavaScript multiple async/awaits behave differently when it awaits promises vs when it awaits functions returning promises?

61 views Asked by At

I have the below code with both the implementations.

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise 1');
  }, 1000);
});

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise 2');
  }, 1000);
})

const p1func = () => new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise 1 func');
  }, 1000);
});

const p2func = () => new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('promise 2 func');
  }, 1000);
})

async function TestPromise() {
  console.log("started");
  const val = await p1;
  console.log(val);

  const val2 = await p2;
  console.log(val2);
  //checkpoint 1: reaches this point in 1 second
  const val3 = await p1func();
  console.log(val3);

  const val4 = await p2func();
  console.log(val4);
  //from checkpoint 1, it takes 2 seconds to reach here
}

TestPromise();

When I ran the code I noticed that when js awaits 2 promises, it starts executing them in parallel & completes within 1 second (asynchronously). When the functions returning promises were run JS ran them one by one (synchronously). Is JS engine detecting 2 awaits on promises prior run in order to be able to execute them in parallel? Why can't it do the same with functions returning promises?

0

There are 0 answers