-2

Can someone help me understand why the following code prints blank? I'm expecting it to print "done" as I assume that the await will make the program wait for the promise to resolve.

Thanks for the help!

var y = '';
async function f() {

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

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

    }

    f().then(console.log(y));

1 Answers1

3

You must pass a callback function to then, not call console.log immediately and pass its return value:

f().then(() => console.log(y));

Of course the code would be much better if you didn't use a global variable but rather returned the value from the async function so that the promise fulfilled with it:

async function f() {
    const promise = new Promise((resolve, reject) => {
        setTimeout(resolve, 1000)
    });
    await promise;
    const result = "done!";
    return result;
}

f().then((y) => console.log(y));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Yep. Even simpler is `async function f() { return new Promise(resolve, reject) => { setTimeout(() => resolve('done!'), 1000); }); }`. If you return a Promise from an async function, the result of the async function is the result of the Promise. No need to have the await. – Jacob Dec 19 '17 at 02:04
  • Wow thanks, that makes sense. That was major oversight on my part. – user2518372 Dec 19 '17 at 02:07
  • 2
    @Jacob [Sure](https://stackoverflow.com/q/43353087/1048572). But if you return a promise, there's no need to have the `async` either in this example :-) Anyway I've updated the code so that it makes a bit more sense to use `async`/`await` here. – Bergi Dec 19 '17 at 02:07
  • Aren't there dozens of dups of this? – jfriend00 Dec 19 '17 at 04:21