JavaScript async/await not awaiting properly?

CaptObvious picture CaptObvious · Apr 18, 2018 · Viewed 8.3k times · Source

I'm having an issue with JavaScript's async/await functions. This is happening on an internal application that I can't share the source for, but I put together a quick generic reproduction of my issue:

I would expect this to return the following with a one second wait between 4 and 5:

1
2
3
4
5
6
"foo"

Instead, after trying this in the console in Chrome 64.0.3282.167 and Firefox 58.0.2 I receive this:

1
2
3
4
6
undefined
5

Please can someone point out where I'm going wrong in this?

Answer

CertainPerformance picture CertainPerformance · Apr 18, 2018

The top-level is running synchronously (as it always does) - it doesn't wait for foo(); to resolve before continuing to console.log("6");. Wrap the calling of foo in something async and await it. You also need to save the return value of foo if you want to display its later:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function baz(input) {
  console.log("4");
  await sleep(1000);
  console.log("5");
  return input;
}

async function bar(input) {
  console.log("3");
  return await baz(input);
}

async function foo() {
  console.log("2");
  const foo = await bar("foo");
  return foo;
}

(async () => {
  console.log("1");
  const str = await foo();
  console.log("6");
  console.log(str);
})();