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:
Please read them thoroughly, and after reading them you will know the "why?" for this article.
"Callbacks" are the functions that are passed as the parameters to some function.
Hello is an example of a Callback.
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".
As the name suggests, a
The syntax for making a
Congratulations, you have made your first
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
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
reject are the inbuilt parameters.
resolve is associated with
reject is associated with
resolve is called on the successful execution of the
reject is called in case of some error, to handle that error, we have
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.
Did you find this article valuable?
Support Saksham Aggarwal by becoming a sponsor. Any amount is appreciated!