A promise is a JavaScript object used to handle asynchronous operations. Before the promise was introduced in JavaScript, events and callback functions were used to handle the asynchronous events. Promises provide a better way of handling multiple callbacks at the same time, thus avoiding the multiple nested callbacks and errors.
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 an argument. The function accepts two functions resolve() and reject().
A Promise has four states:
pending: Once the promise is called, it will start in a pending state i.e. the operation is running. The promise is pending until it resolves, giving the calling function whatever operation/data was being requested.
fulfilled: The created promise will end up in a resolved state, or in a rejected state. ‘fulfilled‘ means a request related to the promise is completed and succeeded. When a promise is resolved successfully .then a callback is used.
rejected: rejected‘ means the action related to the promise has been completed but there is an error. If the promise is rejected or failed, the .catch callback is used to display an error
settled: The promise has either succeeded or rejected, anyway this callback gets called. To settle the promise .finally callback is used
let p = new Promise((resolve, reject) => { const multiplication = 2 * 3; if(multiplication == 6){ resolve("Correct!"); }else { reject("Mistake!"); } }); p.then((resolve)=>{ console.log(`This is the success message ${resolve}`); }).catch((reject)=> { console.log(`This is in the failure message ${reject}`); }).finally(() => { console(' This block will be executed anyway'); });;
The promise is very useful when we need to do something that will take a long time in the background and where we must wait for the output. For example, downloading files from the server and awaiting the response of an API call.
const unsubscribe = true ; const watchedVideo = true; function visitorCallBack() { let promise = new Promise((resolve, reject) => { if(!unsubscribe && !watchedVideo ) { reject({ name: "Neither watched video nor subscribed to the channel", message: "User neither watched video nor subscribed to the channel " }); } else if(!unsubscribe) { reject({ name: "Didn't subscribe", message: "User didn't subscribe to my channel" }); }else if(!watchedVideo) { reject({ name: "Didn't watch video", message: "User didn't watch video" }); }else { resolve({ name: "User watched video and subscribe to my channel", message: "Yeahh, one viewer and subscriber added to the channel" }); } }); return promise; } visitorCallBack().then((resolve) => { console.log(`Success message ${resolve.message}`); }).catch((reject)=> { console.log(`${reject.name}`); });
In the above example, we have used Promise to display the message based on the visitor’s interaction in our channel.
Let’s say we want to upload the different images parallelly at the same time, for that we can use promise.all. Inside Promise.all all the promises that we want to run is passed as an array in argument . The Promise.all runs all of the promises and as soon as it is done, it calls .then and .catch methods depending on the success(resolve) and failure(reject). In Promise.all if one of the promises is rejected, the entire process exits. In our case, all the promises are going to resolve. So, we can use .then. The .then sends an array of all the success messages.
const uploadImageOne = new Promise( ( resolve, reject ) =>{ resolve("Image 1 Uploaded"); }) const UploadImageTwo = new Promise( ( resolve, reject )=> { resolve("Image 2 Uploaded"); }) const uploadImageThree = new Promise( ( resolve, reject ) => { resolve( "Image 3 Uploaded" ); } ); Promise.all([uploadImageOne, UploadImageTwo, uploadImageThree]) .then(message => { //Displays Array of messages console.log(message); });
Instead of displaying all the error messages after completing all the promises, if we want to display a single message based on the promise execution, Promise.race can be used. The Promise.race returns a promise as soon as it is resolved/reject instead of waiting for all the promises to be completed.
Let’s say, if one promise needs to call the database and get the result back and the other two promises are two quick, the other two promises don’t have to wait for the first one to finish. If we want to display the message as soon as one of the images is uploaded, we can use Promise.race instead of Promise.all. As the name suggest, those promises race against each other and it returns the first settled (reject/resolved) promise instead of waiting for everything to be completed because of that it will return a single message.
Promise.race([uploadImageOne, UploadImageTwo, uploadImageThree]) .then(message => { //Displays single message console.log(message); });
If we want to return any resolved promise from the arrays of Promises, Promise.any can be used. The Promise.any returns the first resolved promise.
let promise1 = new Promise( (resolve, reject) => { reject("Better Luck Next Time"); }); let promise2 = new Promise((resolve, reject) => { resolve("Congratulations, you are selected to the next round of interview!"); }); Promise.any([promise1, promise2]) .then( resolveMessage => { console.log("Promise.any", resolveMessage); }) .catch( rejectMessage => { console.log("On Calling Promise.any", rejectMessage); })
Views: 17