【翻译】你需要知道的4个Promise的方法

1,345 阅读2分钟

原文地址: dev.to/kannndev/4-…

大家好 在本文中,我们将看到最常用的4种 Promise 方法。

  • all
  • race
  • any
  • allSettled

1. Promise.all:

Promise.all 方法接受一个 promise 数组,并返回一个新的 promise,当所有 promise 被 resolved 时,该 promise 会 resolved;当其中一个 promise 被 rejected 时,promise.all 方法会被 rejected。

// Example 1:
const dog = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐶'), 1000)
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐈'), 2000)
})

Promise.all([dog, cat]).then((values) => {
  // Order of values will be in the same order 
  // in which promises are present in the array
  console.log(values) // ['🐶', '🐈']
})

// Example 2:
const bear = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐻'), 1000)
})
const panda = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐼'), 2000)
})

Promise.all([bear, panda])
  .then((values) => {
    console.log(values)
  })
  .catch((error) => {
    console.error(error) // 🐻
  })

// Practical Usage:
// This would be useful in the case where 
// you want to fetch data from multiple resources 
// and then consolidate them to form a response 
// before sending it back to the client.
Promise.all([
    fetch('/endpoint0'),
    fetch('/endpoint1'),
    fetch('/endpoint2'),
]).then(response => console.log(response))
.catch(error => console.log(error))

2. Promise.race:

Promise.race 方法接受一个 promise 数组并返回一个新的 Promise,如果任何一个 promise 被 resolved 或 rejected,它都会 resolved 或 rejected。

// Example 1:
const dog = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐶'), 1000)
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐈'), 2000)
})

Promise.race([dog, cat]).then((value) => {
// value will be the resolved value of 
// first promise which resolved.
  console.log(value) // '🐶'
})

// Example 2:
const bear = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐻'), 1000)
})
const panda = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐼'), 2000)
})

Promise.race([bear, panda])
  .then((value) => {
    console.log(value)
  })
  .catch((error) => {
  // value will be the rejected value of 
  // first promise which was rejected.
    console.error(error) // 🐻
  })

// Practical Usage:
// Here Promise will throw 'request timeout' 
// if the api call takes more than 30 seconds
Promise.race([
    fetch('/endpoint'),
    new Promise(function (resolve, reject) {
      setTimeout(() => 
        reject(new Error('request timeout')), 30000)
    })
]).then(response => console.log(response))
.catch(error => console.log(error))

Promise.any:

Promise.any 方法接受一个 Promise 数组并返回一个 Promise,当 Promise 数组中的任何一个 Promise resolved,则它也 resolved。 如果所有的 Promise 都 rejected,则它也rejected。

// Example 1:
const dog = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐶'), 1000)
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐈'), 2000)
})

Promise.any([dog, cat]).then((value) => {
  // value will be the resolved value of 
 // first promise which resolved.
  console.log(value) // '🐈'
})

// Example 2:
const bear = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐻'), 1000)
})
const panda = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐼'), 2000)
})

Promise.any([bear, panda])
  .then((value) => {
    console.log(value)
  })
  .catch((error) => {
  // Array of rejected values
    console.error(error) // ['🐻','🐼']
  })

// Practical Usage:
// This can be used if we have multiple async calls 
// and we are only interested in the first successful one.
Promise.any([
    fetch('/endpoint'),
    fetch('/alternateEndpoint'),
    })
]).then(response => console.log(response))
.catch(error => console.log(error))

注意:在撰写本文时,此功能仍处于试验阶段,尚不受所有浏览器和平台的支持

Polyfill : Promise.any

4. Promise.allSettled:

Promise.allSettled 方法接受一个 Promise 数组,并返回一个新的 Promise,该 Promise 在所有给定的 Promise 都已 resolved 或被 rejected 后进行解析,解析的结果为一个status 字段和一个 value 或者 reason 字段的数组。(resolved 是 value,rejected 是 reason)。

// Example 1:
const dog = new Promise((resolve, reject) => {
  setTimeout(() => resolve('🐶'), 1000)
})
const cat = new Promise((resolve, reject) => {
  setTimeout(() => reject('🐈'), 2000)
})

Promise.allSettled([dog, cat]).then((values) => {
  console.log(values); 
// [{ status: 'fulfilled', value: '🐶' },
// { status: 'rejected', // reason: '🐈' }]
});


// Practical Usage:
// I have mostly used this for batch processing where 
// we identify the failed ones and retry separately.
Promise.allSettled([
    fetch('/endpoint0'),
    fetch('/endpoint1'),
    })
]).then(response => console.log(response))