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

2
  • You are close. Promises have a special place in the event queue in the form of microtasks. This should clarify everything: jakearchibald.com/2015/tasks-microtasks-queues-and-schedules Commented Jan 25, 2018 at 6:39
  • 2
    In your example, pr is already a promise so you would do pr.then(), not pr().then(). pr is not a function. Commented Jan 25, 2018 at 6:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.