Featured Post
A Simple Guide to Promises in JavaScript ES6
- Get link
- X
- Other Apps
A Simple Guide to Promises in JavaScript ES6
In this JavaScript tutorial, based on the freeCodeCamp JavaScript Algorithms and database structures, I will be explaining and walking you through the concept and usage of Promises in JavaScript, with very simple examples to make you understand the concept easily.
What is a Promise in JavaScript?
Imagine a situation whereby you decided to apply for loan to start a new business. You make a loan application letter the next day and approach the Bank Manager. When you submit this application of loan to the bank manager, he says that he will try his best to help you by trying to grant the loan. This is the Promise from the manager to help you get the loan! You are told to wait for 2 days and you are waiting eagerly for the good news. This would be the pending state of your application. After 2 days, the manager calls you and says the loan is granted! Your application is Successful ! This is your fulfilled state of the application. Then, you carry out the required documentations after this approval, in order to continue with the start of your business venture. Then, you go to the bank again to get your loan money and Finally, you launch your Business, with an opening ceremony, when, you invite the bank manager and all other guests concerned. This would be the settled state of the successful application.
Had the bank manager called you to say that your application was rejected, then, you could say, that he did not keep his promise. This would be your rejected state of the application. So, you would not receive the promised amount from the bank and then, you would have to either approach some other bank or source or you would need to end the idea of starting your business venture. This is the settled state of the failed or rejected application.
As you can see in the above example, the promise given by the manager is asynchronous, that is unidirectional. He cannot say simultaneously, "hey, good news, your loan application has been approved and sanctioned AND your loan application has been rejected!" He can only either say " The loan application has been approved" (that is, your application is a Success) or he could say " your application has been rejected." He cannot approve and reject the application simultaneously! So, this whole operation or process of bank loan application to launch a business is an Asynchronous operation. A Promise in JavaScript is similar in nature and synonymous with the above example explained for your complete understanding as a total beginner in JavaScript programming.
Advantages of Promises
- Promises enables smoother flow of Asynchronous operations.
- Promises helps in better handling of errors.
- Promises helps in enhancing code readability.
How To Create A New Promise
Code
const myPromise = new Promise((resolve, reject) =>{
});
Code Explanation
In the above code, we declare a variable, myPromise and pass a constructor function to it with the keyword , new, and it accepts two parameters, resolve and reject, that are used to decide the result or output of the function. As you can see already, we have used the ES6 arrow function to do this code.
The above syntax is the basic syntax structure needed to create a new Promise using the constructor function as shown above. Below, we have been asked to do a task to understand this a bit further.
const makeServerRequest = new Promise((resolve, reject) =>{
});
Complete a Promise with resolve and reject
When you create a a Promise object, you need to note that this object has three states, namely, a pending state, a fulfilled state and a rejected state. The resolve parameter is used when you want to fulfil your promise and the reject parameter is to be used when you want to reject your promise or rather, you want a failed outcome to your promise. Until a promise is fulfilled or rejected, it is in the pending state, since a promise is considered complete, only when it is fulfilled or rejected! This is the reason that we pass the two parameters, resolve and reject to the above function, in order to complete the promise that we created.
Code
const myPromise = new Promise((resolve, reject) =>{
if(place the condition here){
resolve("Promise was fulfilled");
}else{
reject("Promise was rejected");
}
});
Code Assignment
Now, you have been given a task wherein you need to make the promise handle for success and failute. If responseFromServer is true, you need to call the resolve method to successfully complete the promise. Then you need to pass a string to resolve with the value "We got the data". If responseFromServer is false, then, you need to use the reject method and pass it as the string to the parameter "Data not received". Now, you can practice by completing the code below:
Code
const makeServerRequest = new Promise((resolve, reject) =>{
//responseFromServer represents a response from a server
let responseFromServer;
if(responseFromServer) {
// change this line
}else {
//change this line
}
});
Solution for Code Assignment
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer represents a response from a server
let responseFromServer;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
});
Explanation for Code Assignment Solution
Then we declare a variable called responseFromServer,
We then use the if-else condition of JavaScript to handle this promise . If the responseFromServer is true, we need to fulfil the promise, by calling the resolve method. After calling the resolve method, we need to pass the value of the resolved data , in this case, the value is the string "We got the data".
If the responseFromServer is false, then we need to reject the promise, by calling the reject method. After calling the reject method, we need to pass the value of the rejected data, in this case, the value is the string "Data not received"
Handle a Fulfilled Promise with then
Once the Promise is fulfilled, what is the action next to be taken? For this action to be taken, you need the then method. We consider and continue with the task that we started of making a server request in the above example. Based on the response we receive from the server, after we make a server request, we need to take some action. The then method is carried out right after the promise is fulfilled using the resolve method.
Code
myPromise.then(result =>{
});
The result is returned from the argument provided to the resolve method. For the below task, we need to add the then method to the promise and use result as the parameter of its callback function and finally, log the result to the console. So, here, we need to call the then method on the promise. The then method should have a callback function with result as its parameter. We should log the result to the console.
Code
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to true to represent a successful response from a server
let responseFromServer = true;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
});
//add the then method here
//log to console
Solution for Code Assignment
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to true to represent a successful response from a server
let responseFromServer = true;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
});
makeServerRequest.then(result => {
console.log(result);
});
Explanation for Code
Handle a Rejected Promise with catch
catch is the method used when your promise has been
rejected. It is executed immediately after a promise's reject method is called.
Code
myPromise.catch(error => {
});
In this case, we pass the error as the argument, in to the reject method.
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to false to represent an unsuccessful response from a server
let responseFromServer = false;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
});
makeServerRequest.then(result => {
console.log(result);
});
//Add the catch method
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to false to represent an unsuccessful response from a server
let responseFromServer = false;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
});
makeServerRequest.then(result => {
console.log(result);
});
makeServerRequest.catch(error => {
console.log(error);
});
Explanation for Code
Conclusion
- Get link
- X
- Other Apps
Comments
Post a Comment