Reputation: 394
I'm programming with javascript and I stumbled on this code I wonder how and why the code below works:
var test = async () => {
console.log("before");
await setTimeout(() => {
console.log("after");
}, 1000);
};
test();
It log's this:
This is a sample code, but my question is how is this working? setTimeout() doesn't return a Promise (I think) so the async/await pair should not work or is something that I'm missing?
Upvotes: 0
Views: 86
Reputation: 664164
Well, it doesn't work:
async function test() {
console.log("before");
await setTimeout(() => {
console.log("callback");
}, 1000);
console.log("after");
}
test();
You will receive before
- after
- callback
. The await
doesn't stop anything, because - as you recognised - setTimeout
doesn't return a promise. It waits for undefined
and continues with the next statement. Your example just was lacking that next statement, so you couldn't see a difference. Here's a working example:
function delay(t) {
return new Promise(resolve => setTimeout(resolve, t));
}
async function test() {
console.log("before");
await delay(1000);
console.log("after");
}
test();
Upvotes: 3
Reputation: 262
As per MDN Web Docs
If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
So, the await setTimeout
expression is converted to a resolved Promise.
Upvotes: -2