+
perl
->
+
+
abap
+
+
+
adonis
+
+
+
hapi
+
sql
||
hack
+
esbuild
+
+
jest
+
+
mxnet
+
+
+
sails
^
+
+
+
emacs
rocket
+
sublime
echo
===
*
+
+
+
sql
+
tf
+
+
_
perl
+
+
+
phoenix
r
+
+
redis
redis
π
+
+
->
+
+
+
+
java
^
groovy
+
zorin
+
+
+
+
+
+
+
rubymine
rubymine
+
+
+
+
lisp
Back to Blog
Promise.resolve in Node.js: A Complete Guide
JavaScript NodeJS Promises JavaScript

Promise.resolve in Node.js: A Complete Guide

Published Nov 7, 2023

Explore Promise.resolve in JavaScript. Manage non-blocking tasks effectively for browser or Node.js environments.

4 min read
0 views
Table of Contents

Explore Promise.resolve in JavaScript. Manage non-blocking tasks effectively for browser or Node.js environments.

What is Promise.resolve()?

Promise.resolve() is a static method that returns a Promise object that is resolved with a given value. It’s a convenient way to create a promise that is already fulfilled.

Basic Syntax

Promise.resolve(value);

Step-by-Step Examples

Example 1: Basic Usage

// Creating a resolved promise
const resolvedPromise = Promise.resolve("Hello, World!");

resolvedPromise.then(value => {
    console.log(value); // Output: Hello, World!
});

Example 2: Converting Values to Promises

// Converting a plain value to a promise
function getData(useCache) {
    if (useCache) {
        // Return cached data as a promise
        return Promise.resolve({ data: "Cached data" });
    } else {
        // Return actual async operation
        return fetch('/api/data').then(res => res.json());
    }
}

// Usage is the same regardless of the source
getData(true)
    .then(result => console.log(result))
    .catch(error => console.error(error));

Example 3: Promise Chaining

Promise.resolve(5)
    .then(value => value * 2)
    .then(value => value + 3)
    .then(value => {
        console.log(value); // Output: 13
    });

Example 4: Async/Await with Promise.resolve

async function processData() {
    try {
        const result = await Promise.resolve("Processed successfully");
        console.log(result);
        return result;
    } catch (error) {
        console.error("Error:", error);
    }
}

processData();

Example 5: Handling Different Input Types

// Promise.resolve can handle different types of inputs

// 1. Plain values
Promise.resolve(42).then(console.log); // 42

// 2. Arrays
Promise.resolve([1, 2, 3]).then(console.log); // [1, 2, 3]

// 3. Objects
Promise.resolve({ name: "John" }).then(console.log); // { name: "John" }

// 4. Another promise
const existingPromise = new Promise(resolve => {
    setTimeout(() => resolve("Delayed result"), 1000);
});

Promise.resolve(existingPromise).then(console.log); // "Delayed result" after 1 second

// 5. Thenable objects
const thenable = {
    then: function(resolve) {
        resolve("Thenable resolved");
    }
};

Promise.resolve(thenable).then(console.log); // "Thenable resolved"

Example 6: Error Handling Pattern

function safeOperation(value) {
    try {
        if (value < 0) {
            throw new Error("Value must be positive");
        }
        return Promise.resolve(value * 2);
    } catch (error) {
        return Promise.reject(error);
    }
}

safeOperation(5)
    .then(result => console.log("Success:", result))
    .catch(error => console.error("Error:", error.message));

safeOperation(-5)
    .then(result => console.log("Success:", result))
    .catch(error => console.error("Error:", error.message));

Example 7: Database Query Example

const mockDatabase = {
    users: [
        { id: 1, name: "Alice" },
        { id: 2, name: "Bob" }
    ]
};

function getUserById(id) {
    const user = mockDatabase.users.find(u => u.id === id);
    
    if (user) {
        // Return found user as a resolved promise
        return Promise.resolve(user);
    } else {
        // Return rejection for not found
        return Promise.reject(new Error("User not found"));
    }
}

// Usage
getUserById(1)
    .then(user => console.log("Found user:", user))
    .catch(error => console.error(error.message));

Best Practices

  1. Use Promise.resolve() for consistency when you need to ensure a value is wrapped in a promise
  2. Simplify conditional async logic by returning Promise.resolve() for synchronous paths
  3. Test async code more easily by using Promise.resolve() to mock async operations
  4. Avoid unnecessary nesting - Promise.resolve() of a promise returns the same promise

Conclusion

Promise.resolve() is a fundamental building block for promise-based programming in Node.js. It provides a clean way to create resolved promises and ensure consistent async interfaces in your code.