In this tutorial, you will learn about JavaScript promises and promise chaining with the assistance of examples.
In this article, you will learn-
What is a Promise?
A promise in JavaScript is like a promise, all things considered. At the point when we make a promise, in actuality, it is an assurance that we will accomplish something later on. Since promises must be made for what’s to come.
A promise has 2 potential results: it will either be kept when the time comes, or it won’t.
This is likewise the equivalent of promises in JavaScript. At the point when we characterize a promise in JavaScript, it will be resolved when the time comes, or it will get rejected.
In JavaScript, a promise is a decent method to deal with asynchronous operations. It is used to see whether the asynchronous operation is effectively finished or not.
A promise may have one of three states.
- Pending
- Fulfilled
- Rejected
A promise begins in a pending state. That implies the process isn’t finished. In the event that the activity is effective, the process closes in a satisfied state. What’s more, if a mistake happens, the process closes in a rejected state.
For instance, when you demand information from the server by using a promise, it will be in a pending state. At the point when the information shows up effectively, it will be in a fulfilled state. On the off chance that a blunder happens, at that point it will be in a rejected state.
Create a Promise
To create a promise object, we use the Promise() constructor.
let promise = new Promise(function(resolve, reject){ //do something });
The Promise() constructor takes a function as a contention. The function additionally acknowledges two functions resolve() and reject().
In the event that the promise returns effectively, the resolve() function is called. What’s more, if a mistake happens, the reject() function is called.
How about we guess that the program beneath is an asynchronous program. At that point, the program can be taken care of by using a promise.
Example 1: Program with a Promise
const count = true; let countValue = new Promise(function (resolve, reject) { if (count) { resolve("There is a count value."); } else { reject("There is no count value"); } }); console.log(countValue);
Output
Promise {<resolved>: "There is a count value."}
In the above program, a Promise object is made that takes two functions: resolve() and reject(). resolve() is used in the process is successful and reject() is used when a blunder happens in the promise.
The promise is resolved if the value of count is valid.
JavaScript Promise Chaining
Promise are useful when you need to deal with more than one asynchronous task, consistently. For that, we use promise chaining.
You can play out an activity after a promise is resolved using strategies then(), catch() and finally().
JavaScript then () method
The then() method is used with the callback when the promise is effectively fulfilled or resolved.
The syntax of then() method is:
promiseObject.then(onFulfilled, onRejected);
Example 2: Chaining the Promise with then()
// returns a promise let countValue = new Promise(function (resolve, reject) { resolve('Promise resolved'); }); // executes when promise is resolved successfully countValue.then( function successValue(result) { console.log(result); }, ) .then( function successValue1() { console.log('You can call multiple functions this way.'); }, );
Output
Promise resolved You can call multiple functions this way.
In the above program, the then() strategy is used to chain the functions to the promise. The then() technique is considered when the promise is resolved effectively.
You can chain various at that point() techniques with the promise.
JavaScript catch() method
The catch() technique is used with the callback when the promise is rejected or if a mistake happens. For instance,
// returns a promise let countValue = new Promise(function (resolve, reject) { reject('Promise rejected'); }); // executes when promise is resolved successfully countValue.then( function successValue(result) { console.log(result); }, ) // executes if there is an error .catch( function errorValue(result) { console.log(result); } );
Output
Promise rejected
In the above program, the promise is rejected. Furthermore, the catch() technique is used with a promise to deal with the mistake.
JavaScript Promise Versus Callback
Promises are like callback functions in the sense that the two of them can be used to deal with asynchronous tasks.
JavaScript callback functions can likewise be used to perform synchronous tasks.
Their differences can be summarized up in the accompanying focuses:
JavaScript Promise
- The syntax is user-friendly and easy to read.
- Error handling is easier to manage.
Example:
api().then(function(result) { return api2() ; }).then(function(result2) { return api3(); }).then(function(result3) { // do work }).catch(function(error) { //handle any error that may occur before this point });
JavaScript Callback
- The syntax is difficult to understand.
- Error handling may be hard to manage.
Example:
api(function(result){ api2(function(result2){ api3(function(result3){ // do work if(error) { // do something } else { // do something } }); }); });
JavaScript finally() method
You can likewise use the at finally() technique with promises. The finally() technique gets executed when the promise is either resolved effectively or rejected. For instance,
// returns a promise let countValue = new Promise(function (resolve, reject) { // could be resolved or rejected resolve('Promise resolved'); }); // add other blocks of code countValue.finally( function greet() { console.log('This code is executed.'); } );
Output
This code is executed.
JavaScript Promise Methods
There are different techniques accessible to the Promise object.
Method | Description |
all(iterable) | Waits for all promises to be resolved or any one to be rejected |
allSettled(iterable) | Waits until all promises are either resolved or rejected |
any(iterable) | Returns the promise value as soon as any one of the promises is fulfilled |
race(iterable) | Wait until any of the promises is resolved or rejected |
reject(reason) | Returns a new Promise object that is rejected for the given reason |
resolve(value) | Returns a new Promise object that is resolved with the given value |
catch() | Appends the rejection handler callback |
then() | Appends the resolved handler callback |
finally() | Appends a handler to the promise |
To learn more about promises in detail, visit JavaScript Promises.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.