0

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?

Coastpear
  • 374
  • 2
  • 15

2 Answers2

3

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();
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-2

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.

sketchedin
  • 252
  • 1
  • 3
  • 10
  • Read OP's question please – Logar Oct 18 '18 at 15:57
  • Responding to "setTimeout() doesn't return a Promise (I think) so the async/wait pair should not work or is something that I'm missing?" – sketchedin Oct 18 '18 at 15:59
  • I think the real question is : `Is redux-thunk (for example) really needed for async calls or is this a feature of ES6 that is doing some magic?` – Logar Oct 18 '18 at 16:00
  • Besides, the question title : `React and Redux with an async/await call in dispatch method without any middleware working` does not mention anything about settimeout working with async/await – Logar Oct 18 '18 at 16:02
  • That's fair, though I thought the question of _magic_ was worth addressing. – sketchedin Oct 18 '18 at 16:18
  • You were right after all, OP edited it's question and changed the title. Still, await with setTimeout won't work, (well it will work, but with an immediate resolution no matter the timeout) – Logar Oct 18 '18 at 17:17
  • Agreed it won't await for the setTimeout to fire, but it will work as per the definition of using `await` in front of an expression that does not return a promise. – sketchedin Oct 18 '18 at 18:02