JavaScript Promise resolve() Method Tutorial

In this section, we will learn what the Promise resolve() method is and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the Promise object.

What is Promise resolve() Method in JavaScript?

A promise does not necessarily need to begin in a pending state and utilize an executor function to reach a settled state. It is possible to instantiate a promise in the `resolved` state by invoking the `Promise.resolve()` static method.

Promise resolve() Method Syntax:

Promise.resolve(value);

Promise resolve() Method Parameters

The method takes one argument and that is a resolving value. This value could be anything from a simple string value to another promise object. The resolve() method simply passes that argument to the handler.

Promise resolve() Method return value

The return value of this method is a resolved Promise object.

Example: using Promise resolve() method in JavaScript

const prom = Promise.resolve("The promise is resolved");

prom.then(value=>{
  console.log("The resolved handler");
  console.log(value);
},failed=>{
  console.log("The rejection of the 'then' method");
  console.log(failed);
}).finally(()=>{
  console.log("The finally handler");
});

Output:

The resolved handler

The promise is resolved

The finally handler

As you can see, the `onResolved()` handler of the promise `prom` is called. This is because we’ve created a promise via the `resolve()` method, and that means the promise is already resolved.

Note: if we pass another promise object into the `resolve()` method, it will simply pass that promise.

Example: passing a promise object as the argument of resolve() method in JavaScript

const pr = new Promise((resolve, reject)=>{
  reject("The promise rejected");
});
const prom = Promise.resolve(pr);

console.log(prom==pr);

prom.then(value=>{
  console.log("The resolved handler");
  console.log(value);
},failed=>{
  console.log("The rejection of the 'then' method");
  console.log(failed);
}).finally(()=>{
  console.log("The finally handler");
});

Output:

true

The rejection of the 'then' method

The promise rejected

The finally handler

The result of the statement below is true:

console.log(prom==pr);

This proves that if we pass another promise to the `resolve()` method, it will simply pass that promise-object.

Also, the result of the promise that we set as the argument of the `resolve()` method defines which handler should be called.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies