Promises in Javascript
what are promises in javascript ?
Promises in javascript is like promises in real life . It’s like you are promising your parent that in one month you will completely learn javascript , So by end of the month you can successfully finish your promise or you can fail .
In Javascript we use promise to handle asynchronous operation . Promises are easy to manage, when you have multiple asynchronous operations and to handle them if you use callbacks that can lead to unmanageable code which is know as callback hell.
let’s check the simple promise example
let promiseToLearnJavaScript = new Promise((resolve, reject) => {
let isJavaScriptCompleted = true;
if (isJavaScriptCompleted) {
resolve("Successfully learned Javascript");
}
else {
reject('Failed to learn Javascript');
}
})
promiseToLearnJavaScript.then(result => {
console.log(result);
}).catch(error => {
console.log(error.message)
})
Promise
takes a callback function as parameter ,and the callback function has two arguments one in resolve
and another is reject
.These two arguments are function , We call the resolve
function when the task in successful and we call the reject
function when the task is failed .
Now when we executes the promise , then()
gets called when the promise is resolved . then
function takes a callback function as argument , and the callback function has an argument which gives us the result or data which we are passing as parameter of the resolve function .
And if the promise rejects then catch method gets executed . catch method takes a callback function as argument and the callback function has an argument which gives us the result or data which we are passing as parameter of the reject function .
Note : While executing promise you always should handle the promise Rejection by declaring catch method , else you will be getting below warning message .
(node:75559) UnhandledPromiseRejectionWarning: Failed to learn Javascript
Let’s see an example where one promise is depending on another promise.
promise chaining in javascript
let learnBasicJS = function(){
return new Promise((resolve,reject)=>{
resolve("Learned Basic")
})
}
let learnAdvanceJS = function(){
return new Promise((resolve,reject)=>{
resolve("Learned Advance")
})
}
learnBasicJS().then(result=>{
return learnAdvanceJS()
}).then(result=>{
console.log(result);
})
in the above example we have two variables and in both the variables we have stored functions which return Promise. so when we are executing the learnBasicJS()
method it return a promise and we have used then()
method to handle that promise.
If the learnBasicJS promise is resolved then we are executing the learnAdvanceJS()
method and returning the learnAdvanceJS promise .
To handle the learnAdvanceJS
promise again we called then()
method . This way to handle the promises called promise chaining in javascript.
Below example we will see how we can execute promise based on data and how to handle promise rejection in single place.
let learnBasicJS = function(status){
return new Promise((resolve,reject)=>{
if(status){
resolve(true)
}
else{
reject(false)
}
})
}
let learnAdvanceJS = function(status){
return new Promise((resolve,reject)=>{
if(status){
resolve(true)
}
else{
reject(false)
}
})
}
learnBasicJS(true).then(result=>{
return learnAdvanceJS(result)
}).then(result=>{
console.log("Congratulation you have reached till Advance Javascript");
}).catch(error=>{
console.log('You are failed to learn Javascript')
})
promise.all in javascript
all()
method takes the array of promises as argument , when all the promises are fulfilled then it returns a promise. If that promise if fulfilled then executes then()
method, if the promise rejects then the catch()
method gets executed .
Suppose you have a requirement where you have to send message and email to the customer . If sending message and email are successful then the complete process is done , if any of them fails the complete process fails. Check the below code.
let sendMessageToCustomer = function () {
return new Promise((resolve, reejct) => {
let status = true;
if (status) {
resolve("Message Sent")
} else {
reejct(new Error("Failed To send the message"))
}
})
}
let sendEmailToCustomer = function () {
return new Promise((resolve, reejct) => {
let status = true;
if (status) {
resolve("Email Sent")
} else {
reejct(new Error("Failed To send the Email"))
}
})
}
Promise.all([sendMessageToCustomer(), sendEmailToCustomer()]).then(result => {
console.log("Process Completed")
}).catch(error => {
console.log(error.message);
console.log("Complete Process Failed")
})
Promise.race in Javascript
race()
method takes the array of promises as argument. Promise.race()
method returns Promise that promise fulfills or reject when any of the promise in the promise array fullfills or rejects .
In the below example there are three tasks of any of the task is completed then the process is completed if any of the task is failed then the complete process is failed.
let task1 = function () {
return new Promise((resolve, reejct) => {
let status = true;
if (status) {
resolve(true)
} else {
reejct(false)
}
})
}
let task2 = function () {
return new Promise((resolve, reejct) => {
let status = true;
if (status) {
resolve(true)
} else {
reejct(false)
}
})
}
let task3 = function () {
return new Promise((resolve, reejct) => {
let status = false;
if (status) {
resolve(true)
} else {
reejct(false)
}
})
}
Promise.race([task1(), task2() , task3()]).then(result => {
console.log("Process Completed")
}).catch(error => {
console.log("Complete Process Failed")
})
I hope this article is helpful for you , i am very glad to help you thanks for reading