Featured Post

BUILD A TODO LIST IN PYTHON

Image
Build a TODO List in Python Overview The objective is to build a todo list to which we can add items, remove the added items, edit the items and even if required, delete out the entire list itself. We will learn here step by step, how to build the todo list with the above  CRUD (Create, Remove, Update/edit, and Delete ) features.  This is a CRUD list  app  that we are building as we can Create, Remove, Update items in the list and Delete the entire list itself. We will be using Python3 to build this Project. Importing os and time We import time to let the screen pause for a while before clearing  and we import os to clear the screen . Initializing the list We initialize the todo list with an empty list as there are not items added yet to the list and this is represented in the code aby using an empty square braces   toDoList = [] Defining the print list  The def keyword is used to define a function in python. In the below code, we define the function called printList(). When we define

A Simple Guide to Promises in JavaScript ES6


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?

A Promise in JavaScript is an object that displays the final success or failure of an Asynchronous operation.  A Promise in JavaScript is similar to a promise given in real life, meaning, it is Asynchronous, that is, it is unidirectional. When you give a promise to another person, you could either fulfil that promise or reject the promise, but, you can not both fulfil as well as reject a promise given. Similarly, in JavaScript, a Promise is Asynchronous in nature.

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

In order to create a promise object in JavaScript, you need to have a Promise() constructor function, so, basically, Promise is a constructor function with a keyword 'new' to create a new Promise and it takes a function as its argument, having two parameters, namely, resolve and reject.  We will be using different methods to handle the resolve and reject outcomes of the  promise , that will be explained in the later part of this tutorial.

 You may represent this promise function in the following syntax :

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.

 Please note above that you need to use the arrow function in JavaScript ES6, short for ECMAScript-6.


 Let's consider creating a new promise called makeServerRequest and pass in a function with two parameters resolve and reject to this constructor function. Here, the user is trying to make a server request. 

 Code 

  


  const makeServerRequest = new Promise((resolve, reject) =>{



}); 

 

We created a new promise called makeServerRequest by using the variable const makeServerRequest and passed a function in it with the two parameters namely, resolve and reject. We call this function as a constructor function since we create a new object from the old object with the help of the keyword, 'new' and the parameters resolve and reject. This is how you use a constructor function in JavaScript to create a new promise that is Asynchronous in nature.


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.

 The following is the syntax to handle a promise  and would be something like this:

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 

 In the above code, we created a new promise called makeServerRequest and we passed it into  a constructor function with two parameters resolve and reject .

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  

We added the then method to the Promise and we use result as the parameter of the callback function, makeServerRequest and finally, we log the result to the console, to see the output.

In the console output, we see the following output on the screen

//running tests

//tests completed

//console output

We got the data



Navigated to Handle a Fulfilled Promise with then

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.

 Add the catch method to your promise. Use error as the parameter of its callback function and log error to the console.

Code Assignment 

  

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 


  

   

  



  

   

 

Solution for Code Assignment 

  

 

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 

Here what happens is we use the catch method after the promise is unsuccesssful and we try to catch the error by adding the error as the parameter to the callback function makaeServerRequest and after that we log the error to the console. We get the following result as output:

//running tests

//tests completed

//console output

Data not received

This is how we receive the error message after catching the error by using the catch method.


Conclusion

Promises in JavaScript are Asynchronous by nature.

In order to create a JavaScript Promise,  you need to use the constructor function. 
A Promise has three states , namely, pending, fulfilled and rejected states.
You can handle a fulfilled promise with the then method and a rejected promise with the catch method.
Promises enable code readability and efficient handling of Asynchronous operations as well as error handling.

I hope, you enjoyed reading and understanding this tutorial and I will be glad to be of help if there is any further questions or doubts pertaining to this topic.

 

Some related posts :

 

Comments

Popular Posts

Build A Random Quote Machine in React

Welcome to my first Blog Post

How To Fight Programmer's Imposter Syndrome

Top Free Online Websites to Learn Coding

Build A Calculator in React

Guide to Learn Coding Efficiently and Effectively