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.
await setTimeout(meaningfully) becausesetTimeoutdoes not return aPromise.async/awaitis syntactic sugar for working with promises. If the function doesn't return a promise thenawaitdoesn't really help.await setTimeout()has the same effect assetTimeout(). Read the MDN documentation aboutawait.Promiseinstead. (or justawaitaPromise)