2

I'm new at ES6, so I study statement of Javascript.

While testing of async/await, I found some strange behavior.

I wrote the code like this,

const test = async () => {
    await setTimeout(() => {
        console.log("timeout");
    }, 2000);
    await console.log(1);
    await console.log(2);
}

test();

Output is here,

1
2
timeout
[Finished in 2.1s]

I define async to function and await to every line to work synchronize.

Expected output is here,

timeout
1
2
[Finished in 2.1s]

Why this code doesn't work synchronize?

Thanks.

7
  • 3
    You can't await setTimeout (meaningfully) because setTimeout does not return a Promise. Commented Jul 11, 2018 at 0:58
  • async/await is syntactic sugar for working with promises. If the function doesn't return a promise then await doesn't really help. await setTimeout() has the same effect as setTimeout(). Read the MDN documentation about await. Commented Jul 11, 2018 at 1:01
  • 1
    You can't await console.log either. Commented Jul 11, 2018 at 1:01
  • @CertainPerformance Thanks. So how can I fix that code to works properly? Commented Jul 11, 2018 at 1:01
  • Make a function that returns a Promise instead. (or just await a Promise) Commented Jul 11, 2018 at 1:02

1 Answer 1

7

This is how you can achieve the desired output. You can wrap your setTimeout in a Promise and await it.

const test = async () => {
    await new Promise((resolve)=>setTimeout(() => {
        console.log("timeout");
        resolve();
    }, 2000)); 
    console.log(1);
    console.log(2);
}

test();

Sign up to request clarification or add additional context in comments.

6 Comments

It works perfectly. Thanks :)
There isn't really any reason to wrap console.log in a promise though... "You can only await on Promises" That's not true. You can await any value. But if it's not a promise it just returns the value immediately.
Yes, you're right, I'll update my answer
@FelixKling Thanks for a clear answer.
But you can't await console.log either. So probably remove the both useless await too lol
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.