Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript async/await not awaiting properly?

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:

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;
}

console.log("1");
foo();
console.log("6");

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?

like image 572
CaptObvious Avatar asked Jan 28 '23 06:01

CaptObvious


1 Answers

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);
})();
like image 98
CertainPerformance Avatar answered Jan 30 '23 19:01

CertainPerformance