How to use Promise.resolve() in JavaScript? [SOLVED]


Written by - Olorunfemi Akinlua
Reviewed by - Deepak Prasad

Introduction

In JavaScript, promise.resolve is a method that creates a new Promise object that is resolved with a given value. This method is often used when working with asynchronous code, as it allows you to create a Promise that is already settled (i.e., it is either fulfilled or rejected) rather than having to wait for an asynchronous operation to complete.

The syntax would be

Promise.resolve([value|promise]) returns promise

The Promise.resolve() function is a convenience function for creating a promise that is already resolved with a given value. If you pass a promise as the argument to Promise.resolve(), the new promise is bound to the promise you provided and it will be fulfilled or rejected accordingly.

In this article, we will discuss how to use promise.resolve method in JavaScript.

 

Using the promise.resolve method

Let’s us start with some basic promise.resolve code. Here is an example of how promise.resolve might be used:

const resolvedPromise = Promise.resolve("Hello, world!");

resolvedPromise.then((value) => {
    console.log(value); // "Hello, world!"
});

Output

Hello, world!

In this example, the resolvedPromise variable is set to a new Promise that is resolved with the value "Hello, world!". When the then method is called on this Promise, the callback function provided to then is executed with the resolved value as its argument.

We can go further and use the promise.resolve method in more expansive ways. Here is a more advanced example that demonstrates how promise.resolve can be used in conjunction with other asynchronous methods to write clean and efficient code:

const makeRequest = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = {
                success: true,
                message: "Request successful",
            };
            resolve(data);
        }, 1000);
    });
};

const requestPromise = makeRequest().then((data) => {
    return Promise.resolve(data);
});

requestPromise
    .then((data) => {
        if (data.success) {
            console.log(data.message);
        } else {
            throw new Error(data.message);
        }
    })
    .catch((error) => {
        console.error(error.message);
    });

Output

Request successful

In this example, the makeRequest function simulates a server request by returning a new Promise that is resolved after a one-second delay. This Promise is then passed to the then method, which uses promise.resolve to create a new Promise that is already resolved with the returned data. This Promise is then passed to another then method, where the resolved data is checked for success or failure. If the request was successful, a success message is logged to the console. If the request failed, an error is thrown and caught in the catch block, where the error message is logged to the console.

 

Promise.resolve(..) and Promise.reject(..)

A shortcut for creating an already-rejected Promise is Promise.reject(..), so these two promises are equivalent:

var p1 = new Promise( function(resolve,reject){
    reject( "Oops" );
} );

var p2 = Promise.reject( "Oops" );

Promise.resolve(..) is usually used to create an already-fulfilled Promise in a similar way to Promise.reject(..). However, Promise.resolve(..) also unwraps thenable values (as discussed several times already). In that case, the Promise returned adopts the final resolution of the thenable you passed in, which could either be fulfillment or rejection:

var fulfilledTh = {
    then: function(cb) { cb( 42 ); }
};
var rejectedTh = {
    then: function(cb,errCb) {
        errCb( "Oops" );
    }
};

var p1 = Promise.resolve( fulfilledTh );
var p2 = Promise.resolve( rejectedTh );

// `p1` will be a fulfilled promise
// `p2` will be a rejected promise

And remember, Promise.resolve(..) doesn’t do anything if what you pass is already a genuine Promise; it just returns the value directly. So there’s no overhead to  calling Promise.resolve(..) on values that you don’t know the nature of, if one happens to already be a genuine Promise.

 

Summary

The promise.resolve method in JavaScript returns a promise that is resolved with a given value. If the value is a promise, the returned promise will be resolved with the resolved value of that promise. If the value is a thenable (i.e. an object or function with a then method), the returned promise will be "wrapped" in a promise and adopted by the thenable's behavior.

 

References

Promise.resolve() - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment