Impact of Async/Await vs .then on Function Execution

Consider we have the following three functions:

async function A() {
  console.log("Function A");
}

async function B() {
  console.log("Function B - Start");
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Function B - End");
      resolve("Data from B");
    }, 10000);
  });
}

async function C() {
  console.log("Function C");
}

In the first setup, we execute these 3 functions in the following manner -

async function Test() {
  await A();
  const res = await B();
  await C();
}

Test();

The function C() will wait for 10 seconds for B() to execute before executing.

Now let's see the second scenario -

function Test() {
  A();
  B().then((data) => {
    const res = data;
  });
  C();
}

Test();

Here function C() won't wait for function B() to complete execution. It will run immeadiately. Why is this the case?

Here's why C() doesn't wait for B() to complete its execution in the second scenario:

  • A() runs immediately because it doesn't involve any asynchronous operations.

  • B() starts executing, but it returns a promise that resolves after a 10-second delay. However, the code doesn't wait for this promise to resolve before moving on.

  • C() is called right after B(), regardless of whether B() has finished its task or not. This is because C()is not directly chained to the promise returned by B(). Therefore, C()runs immediately after B() is called, without any delay.

If you want C() to wait for B() to complete, C() will need to be in the promise chain created from B().

function Test() {
  A();
  B().then((data) => {
    const res = data;
    C();
  });
}

Test();

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda