Understanding Promises in JavaScript

What is a Promise in JavaScript?

In JavaScript, a promise is exactly what it sounds like. You use it to make a promise to do something, usually asynchronously. When the task completes, you either fulfill your promise or fail to do so. A promise is a JavaScript object that links producing code and consuming code.

In this article, we will learn about promises in JavaScript. Let’s get right into it.

Create a JavaScript Promise

A 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.

Have a look at the example below:

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

});

As you can see, we created a promise called myPromise then we passed in a function with resolve and reject parameters to the constructor.

Complete a Promise with resolve and reject

A promise has three states: pending, fulfilled, and rejected.

The promise we created in the previous example is forever stuck in the pending state because you did not add a way to complete the promise. Theresolve is used when you want your promise to succeed and reject is used when you want it to fail.

Have a look at the example below:

const myPromise = new Promise((resolve, reject) => {
  if(condition here) {
    resolve("Promise was fulfilled");
  } else {
    reject("Promise was rejected");
  }
});

Handle a Fulfilled Promise

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 method thenis executed immediately after your promise is fulfilled with resolve. Here is an example:

myPromise.then(result => {
  // do something with the result.
});

#web-development #programming #javascript #developer

Learn About Promises in JavaScript with Practical Examples
3.00 GEEK