4

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
CaptObvious
  • 83
  • 1
  • 1
  • 7

1 Answers1

8

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);
})();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    Right, but that doesn't explain why it's returning `undefined` rather than `foo`. – CaptObvious Apr 18 '18 at 00:50
  • 1
    `undefined` is the "result" of the last `console.log` ... type `console.log('hello')` in the develoepr tools console ... oputput is `hello` and `undefined` – Jaromanda X Apr 18 '18 at 00:55
  • 2
    It turns out the example I gave doesn't accurately reproduce the issue I'm having. I'm going to repost this question once I've created an accurate reproduction. Since the answer you provided does answer the asked question and may help people in the future, I'm going to go ahead and mark it as the answer. Thanks! – CaptObvious Apr 18 '18 at 00:59