0

I am a bit confused by the two following code snippets:

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  return result; 
}
console.log(f()); //prints Promise { <pending> } at once then wait for 1 second before terminating

And

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  console.log(result); 
}

f(); //waits for 1 second and prints done! before terminating

I was expecting the two code snippets above to produce the same result, e.g. print done! to the console after 1 second. What made the first code snippet return

Yu Zhang
  • 2,037
  • 6
  • 28
  • 42
  • You need to use `await` on `f` as well e.g. `await f()` for it to return what value the promise holds. – kelsny Apr 13 '22 at 14:01
  • #1 logs a promise because `async` functions always return promises. If you want to interact with the eventual value of that promise, either call `.then` on the promise, or put your code in an `async` function and `await` the promise. – Nicholas Tower Apr 13 '22 at 14:01
  • 1
    Nitpick: *"wait until the promise resolves"* No, it waits until the promise *settles*. A promise can be resolved but still be unsettled (aka pending) and in fact they often are. For the distinction, see my short article [Let's talk about how we talk about promises](https://thenewtoys.dev/blog/2021/02/08/lets-talk-about-how-to-talk-about-promises/). – T.J. Crowder Apr 13 '22 at 14:03
  • 1
    you can achieve the same effect in the first case by writing `console.log(await f()); ` instead of `console.log(f()); ` – Alan Omar Apr 13 '22 at 14:04

1 Answers1

2

What made the first code snippet return

Both code snippets return at the same point. The await keyword, when it gets a promise on the RHS, makes the function it belongs to go to sleep until that promise settles.

Meanwhile, the calling function gets the promise returned by f and continues running.

That's the point of using async functions: They don't block when they are dealing with something asynchronous.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335