The asynchronous evolution in javascript
June 12, 2023In the early days of JavaScript, callbacks were the primary way to handle asynchronous code. However, this approach has its limitations and can lead to what is commonly known as "callback hell." As a result, promises were introduced, providing developers with a more elegant solution for handling asynchronous code. More recently, async/await has become the preferred method for handling asynchronous code in JavaScript. Let's dive into it.
Synchronous and Asynchronous
Synchronous and asynchronous are terms used to describe communication or data transfer. Synchronous communication happens in real time, meaning the sender and receiver are both present and active at the same time. Asynchronous communication, on the other hand, does not require that both parties are present and active at the same time. Data or messages can be sent and received at different times.
How to handle asynchronous with single thread
- js ifself is single threaded means that it can not handle asynchronous
- js only has a call stack (and a heap)
Until another guy offers it an js engine that contains resources and served as an environment for js execution
- an environment helping js to do stuff
- a callback queue contains functions pushed in by the environment
- an event loop continuously pop items from the callback queue and push to the call stack when it is empty
JS native wrappers for callback
Callbacks can lead to a confusing and tangled mess of nested functions, also known as callback hell. However, we can use native wrappers to improve the readability and structure of our code.
Promise (from es5)
Promises are one such wrapper that provides a way to work with asynchronous operations in a more organized and readable way. In addition to making the code more concise, promises also allow for better error handling and a more controlled flow of execution.
Async Await (from es6)
Another native wrapper that simplifies asynchronous code is Async Await. This syntax allows you to write asynchronous code that looks like synchronous code, making it easier to reason about and debug. With the introduction of Async Await, the process of handling asynchronous operations has become more streamlined and intuitive for developers.
FQAs
- Is node.js multi-threaded?
→ Yes, although node.js runs javascript in single-threaded, it is multi-threaded itself. → see more
- Is