Dosper7
Dosper7

Reputation: 394

setTimeout working with async-await keywords but don't know how it works

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:

  1. "before"
  2. "after"

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

Answers (2)

Bergi
Bergi

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

sketchedin
sketchedin

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

Related Questions