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.

Hide
  • 3,199
  • 7
  • 41
  • 83
  • 3
    You can't `await setTimeout` (meaningfully) because `setTimeout` does not return a `Promise`. – CertainPerformance Jul 11 '18 at 00: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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await). – Felix Kling Jul 11 '18 at 01:01
  • 1
    You can't await console.log either. – tkausl Jul 11 '18 at 01:01
  • @CertainPerformance Thanks. So how can I fix that code to works properly? – Hide Jul 11 '18 at 01:01
  • Make a function that returns a `Promise` instead. (or just `await` a `Promise`) – CertainPerformance Jul 11 '18 at 01:02
  • Create a function that calls `setTimeout` and returns a promise. – Felix Kling Jul 11 '18 at 01:02
  • @Hide: You can check for answer @ question that I've recently asked here: https://stackoverflow.com/questions/51237862/how-to-make-an-async-then – Isaac Jul 11 '18 at 01:06

1 Answers1

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();
JohanP
  • 5,252
  • 2
  • 24
  • 34