Promise: Web developer's topic in javascript
single-threaded Javascript What is a Promise in javascript? Promise LifecyclePromise constructor consume the promise value then() catch() finally()
Overview
In real life, Promises made by any human could be completed or not. It depends upon time and situation.
Promises make Javascript more efficient and responsive, by allowing us to handle asynchronous code. They are an important concept in modern Javascript programming.
What is single-threaded Javascript?
Javascript is a single-threaded programming language. It means that Javascript can execute one code statement at a time. Javascript can not execute various statements at the same time. It is an interpreting language.
Why use Promises in javascript?
In javascript, some pieces of code execute immediately and some take time because Javascript is single-threaded. When we connect to the server for fetching data, the execution thread would be blocked, leading to a bad user experience due to slow loading. We can solve these problems through Promises.
What is a Promise in Javascript?
Promises allow us to write code that waits for the completion of an asynchronous task before moving on to the next task.
A promise is an object that represents a value that may not be available yet but will be available at some point in the future. It is a way of handling asynchronous code, which means code that runs in the background while another code is executing.
Importance of Javascript Promises
Here are some important Promises.
It makes a cleaner and more manageable way to handle asynchronous code in nest callback to handle callback hell.
It allows us to write code that waits for the completion of an asynchronous task before moving to the next task which makes more efficient and responsive code.
Promises can handle multiple asynchronous tasks in a chained manner that makes it easy to debug and improve over time.
It comes with an inbuilt error-handling mechanism. We can handle both expected and unexpected errors in a consistent way that makes it easier to identify and debug the code.
Promises can be used regardless of the libraries or frameworks because they are widely used.
What is Promise Lifecycle?
We can understand Promise lifecycle by a real-life example.
Suppose, you have a lady, who is your lover. You promise lady to marry her.Then you have several conditions to marry her.
When you make(create) a promise to his lover, it is
pending
in nature because you have not married yet.If you become successful by convincing families of your marriage. It will be treated as
resolved
.If you become fail in your promise then it will be treated as
rejected
.When you declare finally whether you have done marriage or not, it will be a
settled
condition.
Same as the real-life condition, in programming, there are four stages in the promise in javascript. When the Promise object is created, it enters the pending state. The resolved state refers that the asynchronous operation has been completely successful. The rejected state indicates that the asynchronous operation has failed. A promise's settled state refers to the final state of the promise after it has been fulfilled or rejected.
What is a Promise constructor?
A promise constructor is used to create a new Promise object.
Syntax
new Promise(function (resolve, reject) {
// Asynchronous operation
});
Example of promise constructor
Let's make a program with a promise constructor.
We know that Math.random() is a function in the inbuilt library of Javascript which is used for finding a random number between 0(include) and 1(exclude).
We want that if Math.random() outputs a number greater than 0.5, the Promise enters the resolved state. And if Math.random() outputs a number less than 0.5, the promise gets rejected.
Let's write the code inside HTML so that the states of promise visualize more clearly.
Output:
When the code runs into the browser and you inspect it in the console, then you can see the results below in the images.
In the first image Math.random logs number 0.69 and the promise enters in the resolved state. You can see <state> and <value> to click on the dropdown arrow.
It is the result of the code when the number is less than 0.5 and the promise is get rejected. You can also see the details of the promise object.
How to consume the Promise value?
Consuming a promise simply means taking the value obtained from the promise to process another operation. After the creation of promises, either resolved value or rejected value will be available in the process.
There are three methods to consume the promise values.
.then( )
.catch( )
.finally( )
.then( )
The then method allows you to specify a function that should be called when a Promise is fulfilled.
Syntax
Promise.then( callbackfunc(result));
Example
We know that Math.random() is a function in the inbuilt library of Javascript which is used to find a random number between 0(include) and 1(exclude).
We want that if Math.random() outputs a number greater than 0.5, the Promise enters the resolved state. And if Math.random() outputs a number less than 0.5, the promise gets rejected.
We will make a new method then()
for that promise.then() function will pass the resolved value as a result. With the help of the result, we will use it to log.
Let's write the code inside HTML so that the states of promise visualize more clearly.
Output:
After running the code in the browser, we can inspect it in the console of the browser.
.catch( )
The catch method is used to handle the rejected value or unsuccessful value. It is used to specify what should happen when a promise is rejected so that we handle the error appropriately in our code.
syntax
Promise.catch(callback(error));
Example
We know that Math.random() is a function in the inbuilt library of Javascript which is used to find a random number between 0(include) and 1(exclude).
We want that if Math.random() outputs a number greater than 0.5, the Promise enters the resolved state. And if Math.random() outputs a number less than 0.5, the promise gets rejected.
We wil make a new method catch()
for that promise.catch() function will pass the rejected value as an error. With the help of the error, we will use it to log.
Let's write the code inside HTML so that the states of promise visualize more clearly.
Output:
After running the code in the browser, we can inspect it in the console of the browser.
.finally( )
The finally method is used to specify a function that is executed when the promise is settled(i.e., either resolved or rejected).
syntax
Promise.finally(callback);
Example
We know that Math.random() is a function in the inbuilt library of Javascript which is used to find a random number between 0(include) and 1(exclude).
We want that if Math.random() outputs a number greater than 0.5, the Promise enters the resolved state. And if Math.random() outputs a number less than 0.5, the promise gets rejected.
We will make a new method finally()
for that we will know that the promise is finally operated(either resolved or rejected). It will only show a message that the promise is completed finally.
Let's write the code inside HTML so that the states of promise visualize more clearly.
Output:
After running the code in the browser, we can inspect it in the console of the browser.