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

JavaScript Promise

JavaScript Promise

Before studying this chapter, you need to understand what asynchronous programming is; you can refer to:JavaScript Asynchronous Programming

Promise is a class provided by ECMAScript 6, intended for writing complex asynchronous tasks more elegantly.

Promise is an object in JavaScript used to handle asynchronous operations. It represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Simply put, a Promise is a "promise" indicating that a result will be returned at some point in the future (either a successful result or a reason for failure).

A Promise has three states:

Example

const

myPromise

=

new

Promise

(

(

resolve

,

reject

)

=>

{

 

// async operation code

 

 

if

(

/* Operation succeeded */

)

{

    resolve

(

'successful result'

)

;

// Change the Promise state to fulfilled

 

}

else

{

    reject

(

'reason for failure'

)

;

// Change the Promise state to rejected

 

}

}

)

;

Browser support

Since Promise was added in ES6, some older browsers do not support it; only Apple's Safari 10 and Windows Edge 14 or later support ES6 features.

The following shows browser support for Promise:

Chrome 58 Edge 14 Firefox 54 Safari 10 Opera 55

Using Promise

The then() method

then() The method is used to specify the callback functions for when the Promise state becomes fulfilled or rejected.

Example

myPromise.

then

(

 

(

result

)

=>

{

   

// Handle the success case

    console.

log

(

'Success:'

,

result

)

;

 

}

,

 

(

error

)

=>

{

   

// Handle failure case

    console.

error

(

'Failure:'

,

error

)

;

 

}

)

;

The catch() method

catch() The method is specifically used to handle the case where a Promise is rejected.

Example

myPromise

  .

then

(

(

result

)

=>

{

    console.

log

(

'Success:'

,

result

)

;

 

}

)

  .

catch

(

(

error

)

=>

{

    console.

error

(

'Failure:'

,

error

)

;

 

}

)

;

The finally() method

finally() The method executes regardless of the Promise's final state.

Example

myPromise

  .

then

(

(

result

)

=>

{

    console.

log

(

'Success:'

,

result

)

;

 

}

)

  .

catch

(

(

error

)

=>

{

    console.

error

(

'Failure:'

,

error

)

;

 

}

)

  .

finally

(

(

)

=>

{

    console.

log

(

'Operation complete'

)

;

 

}

)

;


Promise chaining

A powerful feature of Promises is the ability to chain multiple asynchronous operations.

Example

doFirstThing

(

)

  .

then

(

(

result

)

=>

doSecondThing

(

result

)

)

  .

then

(

(

newResult

)

=>

doThirdThing

(

newResult

)

)

  .

then

(

(

finalResult

)

=>

{

    console.

log

(

'Final result:'

,

finalResult

)

;

 

}

)

  .

catch

(

(

error

)

=>

{

    console.

error

(

'Error somewhere in the chain:'

,

error

)

;

 

}

)

;


Static Promise methods

Promise.all()

Wait for all Promises to complete, or for any Promise to fail.

Example

Promise.

all

(

[

promise1

,

promise2

,

promise3

]

)

  .

then

(

(

results

)

=>

{

   

// results is an array containing the results of all Promises

    console.

log

(

results

)

;

 

}

)

  .

catch

(

(

error

)

=>

{

   

// This branch is reached if any Promise fails

    console.

error

(

error

)

;

 

}

)

;

Promise.race()

Returns the result of the Promise that settles first (whether fulfilled or rejected).

Example

Promise.

race

(

[

promise1

,

promise2

,

promise3

]

)

  .

then

(

(

result

)

=>

{

   

// Use the result of the Promise that settled first

    console.

log

(

result

)

;

 

}

)

  .

catch

(

(

error

)

=>

{

   

// If the Promise that settled first was rejected

    console.

error

(

error

)

;

 

}

)

;

Promise.resolve() and Promise.reject()

Quickly create a fulfilled or rejected Promise.

Example

const

resolvedPromise

=

Promise.

resolve

(

'Immediately resolved value'

)

;

const

rejectedPromise

=

Promise.

reject

(

'Immediately rejected reason'

)

;


Practical Application Examples

Example 1: Using Promises to handle AJAX requests

Example

function

fetchData

(

url

)

{

 

return

new

Promise

(

(

resolve

,

reject

)

=>

{

   

const

xhr

=

new

XMLHttpRequest

(

)

;

    xhr.

open

(

'GET'

,

url

)

;

    xhr.

onload

=

(

)

=>

{

     

if

(

xhr.

status

===

200

)

{

        resolve

(

xhr.

response

)

;

     

}

else

{

        reject

(

new

Error

(

xhr.

statusText

)

)

;

     

}

   

}

;

    xhr.

onerror

=

(

)

=>

reject

(

new

Error

(

'Network error'

)

)

;

    xhr.

send

(

)

;

 

}

)

;

}

fetchData

(

'https://api.example.com/data'

)

  .

then

(

(

data

)

=>

{

    console.

log

(

'Data fetched successfully:'

,

data

)

;

 

}

)

  .

catch

(

(

error

)

=>

{

    console.

error

(

'failed to get data:'

,

error

)

;

 

}

)

;

Example 2: Using a Promise chain to handle multiple asynchronous operations

Example

function

getUser

(

userId

)

{

 

return

fetch

(

`

/

users

/

$

{

userId

}

`

)

;

}

function

getPosts

(

userId

)

{

 

return

fetch

(

`

/

users

/

$

{

userId

}

/

posts`

)

;

}

getUser

(

123

)

  .

then

(

(

user

)

=>

{

    console.

log

(

'Fetching user info:'

,

user

)

;

   

return

getPosts

(

user.

id

)

;

 

}

)

  .

then

(

(

posts

)

=>

{

    console.

log

(

'Fetching user posts:'

,

posts

)

;

 

}

)

  .

catch

(

(

error

)

=>

{

    console.

error

(

'Operation failed:'

,

error

)

;

 

}

)

;


Common problems and best practices

1. Avoid nesting Promises

Wrong approach (the Promise version of callback hell):

Example

doFirstThing

(

)

.

then

(

(

firstResult

)

=>

{

  doSecondThing

(

firstResult

)

.

then

(

(

secondResult

)

=>

{

    doThirdThing

(

secondResult

)

.

then

(

(

thirdResult

)

=>

{

      console.

log

(

thirdResult

)

;

   

}

)

;

 

}

)

;

}

)

;

Correct approach (using chaining):

Example

doFirstThing

(

)

  .

then

(

doSecondThing

)

  .

then

(

doThirdThing

)

  .

then

(

(

finalResult

)

=>

{

    console.

log

(

finalResult

)

;

 

}

)

;

2. Always handle rejections

Forgetting to handle Promise rejections leads to 'Uncaught Promise rejection' errors. Always use .catch() or try/catch(in async/await) to handle errors.

3. Promises are not cancelable

Once created, a Promise cannot be canceled. If you need cancellation, consider using AbortController or other patterns.

4. Frequently asked questions (FAQ)

Q: Can the then, catch, and finally sequence be reordered?

A: Yes, the effect is exactly the same. But it is not recommended; it is best to write your code in the then-catch-finally order.

Q: Other than the then block, can the other two blocks be used more than once?

A: Yes. Like then, finally executes in order, but only the first catch block runs, unless there is an exception inside a catch block. So it is best to have only one catch and one finally block.

Q: How can a then block be interrupted?

A: A then block executes sequentially by default; return cannot interrupt it, but you can use throw to jump to catch to achieve interruption.

Q: When is it appropriate to use Promises instead of traditional callback functions?

A: When you need to perform multiple asynchronous operations in sequence. For example, if you want to check a username and password asynchronously one after the other, you first check the username asynchronously and then check the password; this is a perfect case for Promises.

Q: Is Promise a way to convert asynchronous operations into synchronous ones?

A: Not at all. Promise is simply a better programming style.

Q: When do we need to write another then instead of continuing in the current then?

A: When you need to call another asynchronous task.


Promises and async/await

ES2017 introduced async/await, which is built on Promises and provides a more intuitive syntax for handling asynchronous operations.

Example

async

function

fetchData

(

)

{

 

try

{

   

const

user

=

await getUser

(

123

)

;

   

const

posts

=

await getPosts

(

user.

id

)

;

    console.

log

(

'User posts:'

,

posts

)

;

 

}

catch

(

error

)

{

    console.

error

(

'failed to get data:'

,

error

)

;

 

}

}

Although async/await is more readable, understanding the basic concepts of Promises is still important because it is the foundation of async/await.