JavaScript is, strictly speaking, synchronous. It behaves asynchronously, though, thanks to its runtime environment — making it, in effect, asynchronous.

These are many questions that you may not know the answer if you haven’t explored what asynchronous JavaScript is. In this article, I would speak of the following and dive deep into asynchronous programming with JavaScript.

  1. The JavaScript event loop
  2. Callbacks and callback hell
  3. Promises
  4. Asynchronous chaining
  5. Async/Await

1. JavaScript Event Loop

With the introduction of ES6, asynchronous programming became very popular in the JavaScript community. Up until then, JavaScript did not have a direct notion of asynchrony introduced. The JavaScript engine does not run in isolation. It runs in a hosting environment. There is a built-in mechanism available in JavaScript runtime called the **event loop. **It handles the execution of multiple chunks of your program over time, each time invoking the JS Engine.

Image for post

When an asynchronous function (e.g., a network request) with a callback is processed, the callstack executes the asynchronous function, and the callback gets added to the callback queue. When the network request completes, the JavaScript runtime removes the asynchronous function from the callstack. Then the event loop picks the next function in the callback queue (this could be the callback function that was last added or a function that was added to the queue earlier) and pushes it to the callstack. Since the callback function was added to the callback queue, it will certainly end up in the callstack sometime in the future. Due to this, the thread is not blocked until a computationally intensive task is complete.

#web-development #asynchronous-programming #javascript #frontend-development #es6

Asynchronous JavaScript: The Event Loop, Callbacks, Promises, and Async/Await
1.80 GEEK