JavaScript ES6 Promises – How JS Promises Work in Single-Threaded Environment

es6javascriptpromises

Javascript is single threaded. What I understand from this is if JS i executing on line of code lets say a function. It cannot go to the next line unless that function has been removed from the stack.

With that being said, I do not understand, how promises let us execute other code blocks down the road, while the interpreter is still resolving the promise code.

I am a noob in JS so I am trying to understand the underlying implementation.

I saw an example PHP implementation of Promises and the idea is that PHP can fork a separate process in a different thread that sends back signal to the main thread when the async code has been executed.

Does it work the same way in Javascript ?

Thanks

Best Answer

Parallel or out of order or asynchronous execution is not really tied to number of threads. Think of it. A single thread can still do the switching and do n things at same time, in bits and pieces. Like a software based CPU.

It's really how the execution platform is implemented. You can have an illusion of such processing via an event queue and a single looper thread that works on that queue.

In case of JavaScript engines, you can think that for every async operation defined on any line in source code, the engine does not wait to complete that operation, rather, simply place it in the queue and cater to it from time to time, until it is completed.

The promised (or future) values contain nothing when the line is executed, and next line is evaluated. Only some time later the values "resolve" and everything depending on that value is also resolved, and so on, until everything is resolved and the queue is empty. Think of a graph being collapsed back to root as values become available and pending calculation complete.