Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Node.js Tutorial

Node HOME Node Intro Node Get Started Node JS Requirements Node.js vs Browser Node Cmd Line Node V8 Engine Node Architecture Node Event Loop

Asynchronous

Node Async Node Promises Node Async/Await Node Errors Handling

Module Basics

Node Modules Node ES Modules Node NPM Node package.json Node NPM Scripts Node Manage Dep Node Publish Packages

Core Modules

HTTP Module HTTPS Module File System (fs) Path Module OS Module URL Module Events Module Stream Module Buffer Module Crypto Module Timers Module DNS Module Assert Module Util Module Readline Module

JS & TS Features

Node ES6+ Node Process Node TypeScript Node Adv. TypeScript Node Lint & Formatting

Building Applications

Node Frameworks Express.js Middleware Concept REST API Design API Authentication Node.js with Frontend

Database Integration

MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert Into MySQL Select From MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join
MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit MongoDB Join

Advanced Communication

GraphQL Socket.IO WebSockets

Testing & Debugging

Node Adv. Debugging Node Testing Apps Node Test Frameworks Node Test Runner

Node.js Deployment

Node Env Variables Node Dev vs Prod Node CI/CD Node Security Node Deployment

Perfomance & Scaling

Node Logging Node Monitoring Node Performance Child Process Module Cluster Module Worker Threads

Node.js Advanced

Microservices Node WebAssembly HTTP2 Module Perf_hooks Module VM Module TLS/SSL Module Net Module Zlib Module Real-World Examples

Hardware & IoT

RasPi Get Started RasPi GPIO Introduction RasPi Blinking LED RasPi LED & Pushbutton RasPi Flowing LEDs RasPi WebSocket RasPi RGB LED WebSocket RasPi Components

Node.js Reference

Built-in Modules EventEmitter (events) Worker (cluster) Cipher (crypto) Decipher (crypto) DiffieHellman (crypto) ECDH (crypto) Hash (crypto) Hmac (crypto) Sign (crypto) Verify (crypto) Socket (dgram, net, tls) ReadStream (fs, stream) WriteStream (fs, stream) Server (http, https, net, tls) Agent (http, https) Request (http) Response (http) Message (http) Interface (readline)

Resources & Tools

Node.js Compiler Node.js Server Node.js Quiz Node.js Exercises Node.js Syllabus Node.js Study Plan Node.js Certificate

Node.js Promises


Introduction to Promises

Promises in Node.js provide a cleaner way to handle asynchronous operations compared to traditional callbacks.

Promises represent the completion (or failure) of an asynchronous operation and its result.

Promise States

  • Pending: Initial state, operation not completed
  • Fulfilled: Operation completed successfully
  • Rejected: Operation failed

Once a promise is settled (either fulfilled or rejected), its state cannot change.


Benefits of Using Promises

With Callbacks

getUser(id, (err, user) => {
  if (err) return handleError(err);
  getOrders(user.id, (err, orders) => {
    if (err) return handleError(err);
    // Process orders...
  });
});

With Promises

getUser(id)
  .then(user => getOrders(user.id))
  .then(orders => processOrders(orders))
  .catch(handleError);

Key Advantages:

  • Flatter code structure (avoids callback hell)
  • Better error handling with single .catch()
  • Easier to compose and chain operations
  • Built-in support for parallel operations

Callback Hell Example (Without Promises)

fs.readFile('file1.txt', (err, data1) => {
  if (err) throw err;
  fs.readFile('file2.txt', (err, data2) => {
    if (err) throw err;
    fs.readFile('file3.txt', (err, data3) => {
      if (err) throw err;
      // Use data1, data2, and data3
    });
  });
});

Creating and Using Promises

Promises can be created using the Promise constructor, which accepts an executor function with two parameters: resolve and reject.

Basic Promise Creation

// Create a new Promise
const myPromise = new Promise((resolve, reject) => {
  // Simulate an async operation (e.g., API call, file read)
  setTimeout(() => {
    const success = Math.random() > 0.5;
    
    if (success) {
      resolve('Operation completed successfully');
    } else {
      reject(new Error('Operation failed'));
    }
  }, 1000); // Simulate delay
});

// Using the Promise
myPromise
  .then(result => console.log('Success:', result))
  .catch(error => console.error('Error:', error.message));
Try it Yourself »

Example: Reading a File with Promises

const fs = require('fs').promises;
const promise1 = Promise.resolve('First result');
const promise2 = new Promise((resolve) => setTimeout(() => resolve('Second result'), 1000));
const promise3 = fs.readFile('myfile.txt', 'utf8'); // Read local file instead of fetch

Promise.all([promise1, promise2, promise3])
  .then(results => {
    console.log('Results:', results);
    // results[0] is from promise1
    // results[1] is from promise2
    // results[2] is the content of myfile.txt
  })
  .catch(error => {
    console.error('Error in one of the promises:', error);
  });
Run example »


Promise Chaining

Promises can be chained to execute asynchronous operations in sequence, with each .then() receiving the result of the previous operation.

Example: Promise Chaining

function getUser(userId) {
  return new Promise((resolve, reject) => {
    // Simulating database call
    setTimeout(() => {
      resolve({ id: userId, name: 'John' });
    }, 1000);
  });
}

function getUserPosts(user) {
  return new Promise((resolve, reject) => {
    // Simulating API call
    setTimeout(() => {
      resolve(['Post 1', 'Post 2', 'Post 3']);
    }, 1000);
  });
}

// Chain the promises
getUser(123)
  .then(user => {
    console.log('User:', user);
    return getUserPosts(user);
  })
  .then(posts => {
    console.log('Posts:', posts);
  })
  .catch(error => {
    console.error('Error:', error);
  });
Try it Yourself »

Promise Methods

Instance Methods

  • then(onFulfilled, onRejected)
    Handles fulfillment or rejection
  • catch(onRejected)
    Handles rejections
  • finally(onFinally)
    Runs after promise settles

Static Methods

  • Promise.all(iterable)
    Waits for all promises to resolve
  • Promise.race(iterable)
    Waits for first promise to settle
  • Promise.allSettled(iterable)
    Waits for all to settle

Utility Methods

  • Promise.resolve(value)
    Creates a resolved promise
  • Promise.reject(reason)
    Creates a rejected promise

Promise.then()

The then() method takes up to two arguments. The arguments are callback functions for the success and failure cases for the Promise.

myPromise
  .then(
    result => console.log(result),
    error => console.error(error)
  );

Promise.catch()

The catch() method handles rejected promises and is equivalent to .then(null, errorHandler).

myPromise
  .then(result => console.log(result))
  .catch(error => console.error(error));

Promise.finally()

The finally() method executes code regardless of whether the promise is fulfilled or rejected.

myPromise
  .then(result => console.log(result))
  .catch(error => console.error(error))
  .finally(() => console.log('Operation completed'));

Promise.all() for Parallel Execution

Promise.all() is used to run multiple promises in parallel, and wait for ALL of them to complete. It fails fast if any promise rejects.

Example: Running Multiple Promises in Parallel

const fs = require('fs').promises;
const promise1 = Promise.resolve('First result');
const promise2 = new Promise((resolve) => setTimeout(() => resolve('Second result'), 1000));
const promise3 = fs.readFile('data.txt', 'utf8'); // Read local file instead of fetch

Promise.all([promise1, promise2, promise3])
  .then(results => {
    console.log('Results:', results);
    // results[0] is from promise1
    // results[1] is from promise2
    // results[2] is the content of data.txt
  })
  .catch(error => {
    console.error('Error in one of the promises:', error);
  });
Run example »

Promise.race() for First Result

Promise.race() is useful when you need the result of the first settled promise, whether it's fulfilled or rejected.

Example: Timeout Pattern with Promise.race()

const promise1 = new Promise(resolve => setTimeout(() => resolve('First result'), 1000));
const promise2 = new Promise(resolve => setTimeout(() => resolve('Second result'), 500));

Promise.race([promise1, promise2])
  .then(result => {
    console.log('Fastest result:', result);
    // Will log 'Second result' because promise2 is faster
  });
Try it Yourself »

Error Handling in Promises

Proper error handling is important.

Promises provide several ways to handle errors:

Example: Error Handling in Promise

function fetchData() {
  return new Promise((resolve, reject) => {
    // Simulating an error
    reject(new Error('Network error'));
  });
}

fetchData()
  .then(
    data => console.log('Data:', data),
    error => console.log('Error handled in then:', error.message)
  );

// Alternative method using catch
fetchData()
  .then(data => console.log('Data:', data))
  .catch(error => console.log('Error handled in catch:', error.message));
Try it Yourself »

Best Practice: Always include error handling with promises using .catch() to prevent unhandled promise rejections, which can lead to silent failures and memory leaks.




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.