In the previous article, we reviewed our understanding of the Nodejs event loop. We understood how Nodejs uses multiple callback queues for different functions and pushes them back on the call stack in a particular priority. In the bonus section, I introduced the microtask queue which is responsible for handling functions deferred using the Promise API. Microtask queue has the highest priority over any other queue, also, it is divided into further two queues: One for the functions deferred using process.nextTick() and other for Promises.

In this article, we will understand what a promise is, what is it doing in the background, and understand its behavior.

Why does Promises exist?

Javascript became popular due to it’s asynchronous nature. Before promises, writing asynchronous code meant writing hugely nested callbacks (callbacks inside callbacks), this meant less intuitive code, longer debugging sessions and huge technical debt. To tackle this issue Promises were introduced in ES6. Motivation for it’s introduction was to avoid callback hell and make asynchronous code more readable.

In a quest to make code more readable, javascript maintainers built an API that is now one of the core fundamentals of javascript.

Promise’s Two Pronged Nature

Image for post

Credits: https://www.deviantart.com/jeepdork

Before Promises, async functions did little in javascript but only passed the callback function to the underlying web api. On the contrary, promises are two pronged, meaning apart from calling the underlying web api they immediately return an object in javascript. To be precise, promises are:

  1. Special objects baked into javascript that gets returned immediately after making an async call (for eg. using fetch). Note that not all async functions support promises out of the box.
  2. Acts a placeholder for the data we hope to get back in future from the underlying web api
  3. Allows you to attach functionality (or functions/callbacks) to be run once the web api returns a value.
  4. Our function/callback is invoked with returned value as input arguments.

#javascript #typescript #promises #nodejs #asynchronous

Mastering JavaScript Promises
1.75 GEEK