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!
setTimeoutare not part of JavaScript, but the runtime. You should look into the event loop and how it works.