skip to Main Content

I am seeing an unexpected output when running some functions using async/await which I can’t work out.

The code looks like:

const delayToRun = async() => {
  console.log('first delay');
  let p = await new Promise((resolve, reject) => {
    setTimeout(() => resolve('Done'), 2000);
  });
  console.log('second delay');
  return p;
};

const start = async() => {
  for (let i = 0; i < 2; i++) {
    const res = await delayToRun();
    console.log(res);
    console.log('--------------------------------');
  }
};

start();
start();

Output:

first delay
first delay
second delay
Done
--------------------------------
first delay
second delay
Done
--------------------------------
first delay
second delay
Done
--------------------------------
second delay
Done
--------------------------------

For me it would make sense that all blocks display: first, second, Done.
But the first one seems to start at the beginning then complete at the end.

Can someone shed some light on this please?

Thanks

2

Answers


  1. You’re not await-ing your start() function, so the second instance of start() is triggered immediately after the first one.

    For comparison:

    delayToRun = async() => {
      console.log("first delay");
      let p = await new Promise((resolve, reject) => {
        setTimeout(() => resolve("Done"), 2000)
      });
      console.log("second delay");
      return p;
    }
    
    start = async() => {
      for (let i = 0; i < 2; i++) {
        const res = await delayToRun();
        console.log(res);
        console.log("--------------------------------");
      }
    }
    
    (async () => {
      await start();
      await start();
    })();
    Login or Signup to reply.
  2. You’re running start() twice, independently, concurrently, since they don’t wait for each other. It might help to understand the behaviour by printing the source of each log line to better distinguish them:

    async function delayToRun(source) {
      console.log(`${source} before delay`);
      const done = await new Promise((resolve, reject) => {
        setTimeout(() => resolve("Done"), 200);
      });
      console.log(`${source} after delay`);
      return done;
    };
    
    async function start(source) {
      for (let i = 0; i < 2; i++) {
        const res = await delayToRun(`${source}, i=${i}`);
        console.log(`${source}, i=${i}: ${res}`);
      }
    };
    
    start("task=1");
    start("task=2");

    But the first one seems to start at the beginning then complete at the end.

    From the output, you can see that actually they execute in lockstep.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search