Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Promise

Node.js Promise

Promise is one of the core concepts for handling asynchronous operations in Node.js.

Promise provides a more elegant way to manage asynchronous code, avoiding the traditional callback hell problem.

This article will introduce the concepts, usage, and common patterns of Promise in detail.


What is a Promise?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states:

  1. Pending (waiting): the initial state, neither successful nor failed
  2. Fulfilled (success): the operation completed successfully
  3. Rejected (failure): the operation failed

Once a Promise's state changes (from pending to fulfilled or rejected), it will not change again.


Create a Promise

In Node.js, you can use the Promise constructor to create a new Promise object:

Example

const

myPromise

=

new

Promise

(

(

resolve

,

reject

)

=>

{

 

// Asynchronous operation

 

const

success

=

true

;

// Assume this is the result of an asynchronous operation

 

 

if

(

success

)

{

    resolve

(

'Operation successful!'

)

;

// State changes to fulfilled

 

}

else

{

    reject

(

'Operation failed!'

)

;

// State changes to rejected

 

}

}

)

;


Using Promises

Promise provides the .then() and .catch() method to handle both success and failure cases:

Example

myPromise

  .

then

(

(

result

)

=>

{

    console.

log

(

result

)

;

// Output: "Operation successful!"

 

}

)

  .

catch

(

(

error

)

=>

{

    console.

error

(

error

)

;

// Output: "Operation failed!"

 

}

)

;


Promise chaining

The power of Promise lies in chaining multiple asynchronous operations:

Example

function

asyncOperation1

(

)

{

 

return

new

Promise

(

(

resolve

)

=>

{

    setTimeout

(

(

)

=>

resolve

(

'Step one complete'

)

,

1000

)

;

 

}

)

;

}

function

asyncOperation2

(

data

)

{

 

return

new

Promise

(

(

resolve

)

=>

{

    setTimeout

(

(

)

=>

resolve

(

`$

{

data

}

,

step two complete`

)

,

1000

)

;

 

}

)

;

}

asyncOperation1

(

)

  .

then

(

(

result

)

=>

asyncOperation2

(

result

)

)

  .

then

(

(

finalResult

)

=>

{

    console.

log

(

finalResult

)

;

// Output: "Step one complete, step two complete"

 

}

)

  .

catch

(

(

error

)

=>

{

    console.

error

(

'Error in chain:'

,

error

)

;

 

}

)

;


Static Promise methods

Promise provides several useful static methods:

Promise.all()

Wait for all Promises to fulfill, or for any one Promise to reject:

Example

const

promise1

=

Promise.

resolve

(

'first'

)

;

const

promise2

=

Promise.

resolve

(

'second'

)

;

Promise.

all

(

[

promise1

,

promise2

]

)

  .

then

(

(

results

)

=>

{

    console.

log

(

results

)

;

// Output: ['first', 'second']

 

}

)

;

Promise.race()

Returns the Promise that first fulfills or rejects:

Example

const

promise1

=

new

Promise

(

(

resolve

)

=>

setTimeout

(

resolve

,

500

,

'first'

)

)

;

const

promise2

=

new

Promise

(

(

resolve

)

=>

setTimeout

(

resolve

,

100

,

'second'

)

)

;

Promise.

race

(

[

promise1

,

promise2

]

)

  .

then

(

(

result

)

=>

{

    console.

log

(

result

)

;

// Output: "second"

 

}

)

;


Error handling

Promise error handling can be implemented through the .catch() or .then() second parameter of:

Example

someAsyncFunction

(

)

  .

then

(

   

(

result

)

=>

{

/* Handle success */

}

,

   

(

error

)

=>

{

/* Handle failure */

}

 

)

;

// Or

someAsyncFunction

(

)

  .

then

(

(

result

)

=>

{

/* Handle success */

}

)

  .

catch

(

(

error

)

=>

{

/* Handle all errors */

}

)

;


async/await Syntax

ES2017 introduced the async/await syntax, making the use of Promise more intuitive:

Example

async

function

runOperations

(

)

{

 

try

{

   

const

result1

=

await asyncOperation1

(

)

;

   

const

result2

=

await asyncOperation2

(

result1

)

;

    console.

log

(

result2

)

;

 

}

catch

(

error

)

{

    console.

error

(

error

)

;

 

}

}

runOperations

(

)

;


Best Practices

  1. Always handle errors: Do not ignore .catch() or try-catch
  2. Avoid nesting: use chaining or async/await to keep code flat
  3. Name Promises: give Promise variables meaningful names
  4. Return Promises: return Promises from functions to enable chaining