DEV Community

Randy Rivera
Randy Rivera

Posted on

Create a JavaScript Promise

A promise in JavaScript is basically what it sounds like. You use it to make a promise to do something. When the task completes, you either fulfill your promise or fail to do so. Promise is a constructor function, so you need to use the new keyword to create one. It takes a function, as its argument, with two parameters - resolve and reject. These are methods used to determine the outcome of the promise.

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

});
Enter fullscreen mode Exit fullscreen mode

Complete a Promise with resolve and reject

A promise has three states: pending, fulfilled, and rejected. The promise you created in the last challenge is forever stuck in the pending state because you did not add a way to complete the promise. The resolve and reject parameters given to the promise argument are used to do this. resolve is used when you want your promise to succeed, and reject is used when you want it to fail. These are methods that take an argument, as seen below.

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

  if(responseFromServer) {
     resolve("We got the data");
  } else {  
     reject("Data not received");
  }
});
Enter fullscreen mode Exit fullscreen mode

Here we just made the promise handle success and failure. If responseFromServer is true, call the resolve method to successfully complete the promise. Pass resolve a string with the value We got the data. If responseFromServer is false, use the reject method instead and pass it the string: Data not received.

Handle a Fulfilled Promise with then

Promises are most useful when you have a process that takes an unknown amount of time in your code (i.e. something asynchronous), often a server request. When you make a server request it takes some amount of time, and after it completes you usually want to do something with the response from the server. This can be achieved by using the then method. The then method is executed immediately after your promise is fulfilled with resolve.

  • Like so:
makeServerRequest.then(result => {
   console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

result comes from the argument given to the resolve method.

Also, 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.

  • Like so:
makeServerRequest.then(result => {
   console.log(result);
});

makeServerRequest.catch(error => {
  console.log(error);
});
Enter fullscreen mode Exit fullscreen mode

error is the argument passed in to the reject method.

Top comments (0)