0

I'm new in javascript, coming from firmware / embedded system / RTOS background. I don't understand the concept of the context switching for JS promise.

For this script:

setTimeout(() => { console.log("Hello"); }, 3000);

I can understand that the callback is registered in event loop task, the script continues until finish and exit. The the event loop run and executes any task / callback that is due.

For this script:

var pr = new Promise(function(resolve, reject) {
    setTimeout(() => { resolve() }, 3000);
});
pr().then(() => { 
    console.log("Hello"); 
});

Does it mean that the script will run pr(), exit the script, run the event loop. Once event loop executes the callback (calling resolve()), the JS will switch context to the script again, and run anything inside then() clause ?

Or the script will run until finish, but the then() clause is registered as callback in event queue when resolve() is called. Then the event queue will execute the then() clause ?

Thank you for your help

daniel.widyanto
  • 1,609
  • 2
  • 13
  • 9
  • You are close. Promises have a special place in the event queue in the form of microtasks. This should clarify everything: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/ – nem035 Jan 25 '18 at 06:39
  • 2
    In your example, `pr` is already a promise so you would do `pr.then()`, not `pr().then()`. `pr` is not a function. – jfriend00 Jan 25 '18 at 06:40

1 Answers1

2

The second, rather. Promises are just an abstraction atop callbacks, there's no magic going on here.

The script runs until completion, creating the promise and calling setTimeout (which installs its callback on the timer) and calling then (which installs its callback on the promise). Then the event loop will advance and run timeout callback, which calls resolve which in turn leads to the promise callback to be executed.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375