Search code examples
javascriptasynchronousasync-awaites6-promise

How is it possible to have asynchronous none blocking code in JavaScript when JavaScript is a single threaded language?


I am new to JavaScript and I am used to being able to create asynchronous none blocking code in Java by creating worker threads.

I don't understand how asynchronous none blocking code works in JavaScript given that JavaScript is a single threaded language.

For example, Promises and Callbacks in JavaScript.

Both are none blocking, and allow the main thread to keep executing the rest of the program line by line and only when the promise is fulfilled at a later time (ex: data is ready) then the promise.resolve() or a callback is executed.

Now, I am having hard time understanding which thread is exactly keeping track of when the promise is fulfilled/ready or a callback is ready to execute if the main thread has already moved on and is busy doing different things?

My logic tells me as a Java programmer that there must be a background worker thread that is in charge of notifying the main thread when a callback/promise is ready to be executed, which contradicts the fact that JavaScript is single threaded, so I must be wrong.

I would love a nice explanation of this concept. Thanks in advance!


Solution

  • There are two ways to achieve concurrent behavior using computers:

    1. You run two computers (or processors) at the same time (multithreading).

    2. You switch between different tasks very fast, so that it looks as if they would run at the same time (multitasking).

    Now while Java switches between those tasks very often, JavaScript only switches the task whenever the current task has finished; therefore, the code does not run concurrently and behaves "single-threaded".

    That JavaScript is executed in a "single-threaded way" doesn't mean that the underlying engine is single threaded. It isn't and it uses some threads to manage I/O. Whenever you start an asynchronous action, the engine delegates it to one background thread; then, when the task is done the other thread returns the result back to the main thread which will then call back into the JavaScript code.

    You could think of the JavaScript engine as a TaskExecutor that starts Threads in a ThreadPool. You do, however, only control the TaskExecutor.