Uncovering Callbacks and Promises in JavaScript

Uncovering Callbacks and Promises in JavaScript

INTRODUCTION

Hi, Programmers, I hope all of you are doing great. This article is in continuation with the last 2 articles I published. Here are the links to those:

  1. Solving Concurrency Challenges

  2. Mastering Event Loops

Please read them thoroughly, and after reading them you will know the "why?" for this article.

CALLBACKS

"Callbacks" are the functions that are passed as the parameters to some function.

Hello is an example of a Callback.

In the article on "Asynchronous Javascript", we ended with Event Handlers. We also discussed that Event Handlers are a type of Callback. We want to perform a task when an event is fired. Earlier these callbacks were used to execute the Asynchronous piece of code. For example, making an HTTP request, making query requests to the servers etc. However, the problem arises when the callback needs to call a function that needs a callback as a parameter. We then see something, which is called a "Callback Hell" or "Pyramid of Doom".

CALLBACK HELL

As you can see, in the above picture, we are having nested callbacks, and the code has become very difficult to read. A pyramid-like structure is formed, thus it is known by the name "Pyramid of Doom". If some error occurs, it will be very difficult to trace that error. Hence, we can conclude that although callbacks can be used to write asynchronous pieces of code, they are not a sustainable solution. This marks the beginning of our next topic, "Promises".

PROMISES

As the name suggests, a promise in Javascript is a promise made to the maker of that promise, that a particular task will be executed when the conditions are met.

The syntax for making a Promise in JavaScript,

Congratulations, you have made your first Promise in JavaScript.

Now, let us see how Promise solves the problem. Consider this,

Suppose, we have a function beforePromise , inside it we have an Asynchronous piece of code. Suppose we want to call a function after that Asynchronous piece of code is executed, we will have to tell that task at that time only. In the above case, it is the function fn.

Now, let us see what difference a Promise creates.

In Promises, we can put that code( which is to be called after the Asynchronous task is completed), inside a then or a catch block. resolve and reject are the inbuilt parameters. resolve is associated with then, and reject is associated with catch. resolve is called on the successful execution of the Promise. reject is called in case of some error, to handle that error, we have catch.

then is executed if the Promise is resolved, while catch is executed if the Promise is not resolved.

Let us wrap this article here. We will discuss more about Promises in the next article.

Happy Coding!

Did you find this article valuable?

Support WEB DEVOLOPMENT by becoming a sponsor. Any amount is appreciated!