Discover Promises in Node.js | Node.js Learn
On this page Promise States Basic Syntax of a Promise Handling Promises with .then(), .catch(), and .finally() Chaining Promises Using Async/Await with Promises Top-Level Await Promise-based Node.js APIs Advanced Promise Methods Promise.all Promise.allSettled Promise.race Promise.any Promise.reject() and Promise.resolve() Promise.try Promise.withResolvers Error Handling with Promises Scheduling Tasks in the Event Loop queueMicrotask process.nextTick setImmediate When to Use Each Discover Promises in Node.js A Promise is a special object in JavaScript that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Essentially, a Promise is a placeholder for a value that is not yet available but will be in the future. Think of a Promise like ordering a pizza: you don't get it right away, but the delivery person promises to bring it to you later. You don't know exactly when, but you know the outcome will either be "pizza delivered" or "something went wrong." Promise States A Promise can be in one of three states: Pending : The initial state, where the asynchronous operation is still running.
Fulfilled : The operation completed successfully, and the Promise is now resolved with a value. Rejected : The operation failed, and the Promise is settled with a reason (usually an error). When you order the pizza, you're in the pending state, hungry and hopeful. If the pizza arrives hot and cheesy, you've entered the fulfilled state. But if the restaurant calls to say they've dropped your pizza on floor, you're in the rejected state.
Regardless of whether your dinner ends in joy or disappointment, once there's a final outcome, the Promise is considered settled . Basic Syntax of a Promise One of the most common ways to create a Promise is using the new Promise() constructor. The constructor takes a function with two parameters: resolve and reject . These functions are used to transition the Promise from the pending state to either fulfilled or rejected .
If an error is thrown inside the executor function, the Promise will be rejected with that error. The return value of the executor function is ignored: only resolve or reject should be used to settle the Promise. const myPromise = new Promise ( ( resolve , reject ) => { const success = true ; if ( success ) { resolve ( ' Operation was successful! ' ) ; } else { reject ( ' Something went wrong. ' ) ; } } ) ; JavaScript In the above example: If the success condition is true , the Promise is fulfilled and the value 'Operation was successful!' is passed to the resolve function.
If the success condition is false , the Promise is rejected and the error 'Something went wrong.' is passed to the reject function. Handling Promises with .then() , .catch() , and .finally() Once a Promise is created, you can handle the outcome by using the .then() , .catch() , and .finally() methods. .then() is used to handle a fulfilled Promise and access its result. .catch() is used to handle a rejected Promise and catch any errors that may occur. .finally() is used to handle a settled Promise, regardless of whether the Promise resolved or rejected. const myPromise = new Promise ( ( resolve , reject ) => { const success = true ; if ( success ) { resolve ( ' Operation was successful! ' ) ; } else { reject ( ' Something went wrong. ' ) ; } } ) ; myPromise . then ( result => { console . log ( result ) ; // This will run if the Promise is fulfilled } ) . catch ( error => { console . error ( error ) ; // This will run if the Promise is rejected } ) . finally ( () => { console . log ( ' The promise has completed ' ) ; // This will run when the Promise is settled } ) ; JavaScript Chaining Promises One of the great features of Promises is that they allow you to chain multiple asynchronous operations together.
When you chain Promises, each .then() block waits for the previous one to complete before it runs. const { setTimeout : delay } = require ( ' node:timers/promises ' ) ; const promise = delay ( 1000 ) . then ( () => ' First task completed ' ) ; promise . then ( result => { console . log ( result ) ; // 'First task completed' return delay ( 1000 ) . then ( () => ' Second task completed ' ) ; // Return a second Promise } ) . then ( result => { console . log ( result ) ; // 'Second task completed' } ) . catch ( error => { console . error ( error ) ; // If any Promise is rejected, catch the error } ) ; JavaScript Using Async/Await with Promises One of the best ways to work with Promises in modern JavaScript is using async/await .
This allows you to write asynchronous code that looks synchronous, making it much easier to read and maintain. async is used to define a function that returns a Promise. await is used inside an async function to pause execution until a Promise settles. async function performTasks () { try { const result1 = await promise1 ; console . log ( result1 ) ; // 'First task completed' const result2 = await promise2 ; console . log ( result2 ) ; // 'Second task completed' } catch ( error ) { console . error ( error ) ; // Catches any rejection or error } } performTasks () ; JavaScript In the performTasks function, the await keyword ensures that each Promise is settled before moving on to the next statement.
This leads to a more linear and readable flow of asynchronous code. Essentially, the code above will execute the same as if the user wrote: promise1 . then ( function ( result1 ) { console . log ( result1 ) ; return promise2 ; } ) . then ( function ( result2 ) { console . log ( result2 ) ; } ) . catch ( function ( error ) { console . log ( error ) ; } ) ; JavaScript Top-Level Await When using ECMAScript Modules , the module itself is treated as a top-level scope that supports asynchronous operations natively.
This means that you can use await at the top level without needing an async function. import { setTimeout as delay } from ' node:timers/promises ' ; await delay ( 1000 ) ; JavaScript Async/await can be much more intricate than the simple examples provided. James Snell, a member of the Node.js Technical Steering Committee, has an in-depth presentation that explores the complexities of Promises and async/await. Promise-based Node.js APIs Node.js provides Promise-based versions of many of its core APIs, especially in cases where asynchronous operations were traditionally handled with callbacks.
This makes it easier to work with Node.js APIs and Promises, and reduces the risk of "callback hell." For example, the fs (file system) module has a Promise-based API under fs.promises : const fs = require ( ' node:fs ' ) . promises ; // Or, you can import the promisified version directly: // const fs = require('node:fs/promises'); async function readFile () { try { const data = await fs . readFile ( ' example.txt ' , ' utf8 ' ) ; console . log ( data ) ; } catch ( err ) { console . error ( ' Error reading file: ' , err ) ; } } readFile () ; JavaScript In this example, fs.readFile() returns a Promise, which we handle using async/await syntax to read the contents of a file asynchronously.
Advanced Promise Methods JavaScript's Promise global provides several powerful methods that help manage multiple asynchronous tasks more effectively: M Promise.all Promise . all (): void This method accepts an array of Promises and returns a new Promise that resolves once all the Promises are fulfilled. If any Promise is rejected, Promise.all() will immediately reject. However, even if rejection occurs, the Promises continue to execute.
When handling a large number of Promises, especially in batch processing, using this function can strain the system's memory. const { setTimeout : delay } = require ( ' node:timers/promises ' ) ; const fetchData1 = delay ( 1000 ) . then ( () => ' Data from API 1 ' ) ; const fetchData2 = delay ( 2000 ) . then ( () => ' Data from API 2 ' ) ; Promise . all ([ fetchData1 , fetchData2 ]) . then ( results => { console . log ( results ) ; // ['Data from API 1', 'Data from API 2'] } ) .
The rest of this page is on the live site.