In React, Promises are stand-in for a value that isn’t always known at the time the promise is made. It enables you to link handlers to the ultimate success or failure value of an asynchronous action. This enables asynchronous methods to return results similarly to synchronous methods: rather than delivering the result right away, the asynchronous function returns a promise to provide the result at a later time.
One of three statuses are possible for a promise.
- Pending
- Fulfilled
- Rejected
Events and callback functions were used before promises, but they had limited functionality and resulted in unmanageable code.
The callback nightmare that would result from having several callback functions would make the code unmanageable. Additionally, managing several callbacks at once is difficult for any user.
Events struggled to manage asynchronous tasks.
What is Asynchronous :
Asynchronous programming is a technique that allows your software to begin a work that could take a while to complete while still being able to respond to other events without having to wait until that task is complete. When that task is complete, the outcome is displayed to your software.
Syntax:
let promise = new Promise(function(resolve, reject){ //do something });
A function is passed as an input to the Promise() function Object(). Additionally, the method accepts the functions refuse and resolve().
When a promise is successfully fulfilled, the resolve() function is used. The reject() function is also called in the event of an error.
JavaScript then() method:
The then() method is used with the callback when the promise is successfully fulfilled or resolved.
We have learned about Promises , Javascript then() method, and Asynchronous similarly you might also like The power of the React Key Attribute: Efficient list building.
Example:
let p =new promise((resolve,reject) =>{ let a= 1+1 if(a==2){ resolve('success') }else{ reject('failed') } }) p.then((message) =>{ console.log('this is in the',message) })catch((message)=>{ console.log('this is in the',message) })
Output: this is in the success.
Chaining Promises in JavaScript:
When you need to manage multiple asynchronous tasks sequentially, promises come in handy. We employ promise chaining for this.
Using the methods then(), catch(), and finally, you can carry out an action once a promise is fulfilled ().
Example:
promiseObject.then(onFulfilled, onRejected); let countValue = new Promise(function (resolve, reject) { resolve("Promise resolved"); }); countValue .then(function successValue(result) { console.log(result); }) .then(function successValue1() { console.log("call multiple function"); });
Output: Promise resolved
call multiple function
Javascript catch():
When a promise is either refused or an execution problem occurs, the catch() method is called. Every time there is a probability of receiving an error at any phase, it is used as an error handler.
Example:
var promise = new Promise(function(resolve, reject) { throw new Error('Some error has occurred') }) promise .then(function(successMessage) { console.log(successMessage); }) .catch(function(errorMessage) { //error handler function is invoked console.log(errorMessage); });
Output: Some error has occurred
Callback vs. Promise in JavaScript:
Promises and callback functions are comparable to one another in that both can be used to manage asynchronous processes.
Synchronous actions can also be carried out through JavaScript callback functions.
JavaScript Promise:
1) The syntax is simple to understand and read.
2) Error management is simpler to control.
Example:
const userLeft = false const userWatchingCatMeme = true function watchPromise(){ return new promise((resolve,reject)=>{ if(userLeft){ reject({ name:'user Left', message:':(' }) }else if(userWatchingCatMeme){ reject({ name:'user watch cat Meme', message:'webdev' }) }else{ resolve('Thumb up') } }) } watchPromise().promise().then((message)=>{ console.log('success:'+ message) }).catch((error)=>{ console.log(error.name+ ' ' +error.message) }) });
Output: user watch cat Meme Webdev
Several promise calls at once:
const recordVideoOne = new promise((resolve,reject)=>{ resolve('video 1 Recorded') }) const recordVideoTwo = new promise((resolve,reject)=>{ resolve('video 2 Recorded') }) const recordVideoTree = new promise((resolve,reject)=>{ resolve('video 3 Recorded') }) promise.all([ recordVideoOne, recordVideoTwo, recordVideoTree ]).then((message)=>{ console.log(message) })
Output: video 1 Recorded
video 2 Recorded
video 3 Recorded
If we written promise.race show single value in output. Like
promise.race([ recordVideoOne, recordVideoTwo, recordVideoTree ]).then((message)=>{ console.log(message) })
Output: video 1 Recorded
Conclusion:
An object that contains the outcome of an asynchronous operation is called a promise.A promise begins in the pending stage and might be fulfilled, rejected, or in between.When a promise is made, use the then() method to schedule a callback to be executed, and when a promise is rejected, use the catch() method to schedule a callback to be triggered.