DEV Community

Discussion on: Why .then run first before the actual promise

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.