DEV Community

Mac Dalwin
Mac Dalwin

Posted on

Why .then run first before the actual promise

async function test(){
await setTimeout(() => {
console.log('run first');
}, 1000)
}
test().then(console.log('finished'));

Output
//finished
//run first.

Why is the callback being executed before the actual promise?
I know setTimeout causes a delay in the callstack but that is why promises/asyncs are being created, to wait until a script finish execution before moving to the then callback.

What am I not getting right about promises or my code.

Mind you: I know async await shouldn't be used in code like the example above but just using it to illustrate same issue I had with my actually code in node

Top comments (2)

Collapse
 
sgoulas profile image
sgoulas

Because setTimeout actually returns a positive integer ID which can be used later to cancel the timeout before it expires. This integer is returned immediately so it is effectively the same as using await on a number, e.g 'await 5'.

On the other hand, the console.log statement will be executed after 1000ms.

So the timeline of events is:

  1. You await for an integer, it gets wrapped in an implicit Promise which is immediately resolved.

  2. The 'then' clause is executed since the promise was resolved, you see 'finished' in the console.

  3. 1000ms pass, the timeout expires and you see the 'run first' message.

Collapse
 
pentacular profile image
pentacular • Edited

Did you mean to write something like this?

test().then(() => console.log('finished'));

then wants an operation to run later.