Promise

Constructor

Promise

  • 描述:封装一个 Promise
  • 语法new Promise(executor)
  • 参数
    • executor(resolve?, reject?):构造函数
      • resolve:兑现一个 promise
      • reject:拒绝一个 promise
let p = new Promise((resolve, reject) => {
    resolve(1)
}) // fulfilled 1

Static Methods

all

  • 语法Promise.all(iterable)
  • 返回值
    • fulfilled:所有 promise fulfilled
    • rejected:任意 promise rejected
Promise.all([Promise.resolve(1), Promise.resolve(2)]) // fulfilled [1, 2]
Promise.all([Promise.resolve(1), Promise.reject(2)]) // rejected 2

any

  • 语法Promise.any(iterable)
  • 返回值
    • fulfilled:任意 promise fulfilled
    • rejected:所有 promise rejected
Promise.any([Promise.resolve(1), Promise.resolve(2)]) // fulfilled 1
Promise.any([Promise.reject(1), Promise.reject(2)]) // rejected AggregateError

race

  • 语法Promise.race(iterable)
  • 返回值
    • fulfilled:任意 promise fulfilled
    • rejected:任意 promise rejected
Promise.race([Promise.resolve(1), Promise.reject(2)]) // fulfilled 1
Promise.race([Promise.reject(1), Promise.resolve(2)]) // rejected 1

allSettled

  • 语法Promise.allSettled(iterable)
  • 返回值
    • fulfilled:所有 promise fulfilled or rejected
Promise.allSettled([Promise.resolve(1), Promise.reject(2)]) // fulfilled [1, 2]

resolve

  • 语法Promise.resolve(value)
  • 返回值fulfilled
Promise.resolve(1) // fulfilled 1

reject

  • 语法Promise.reject(value)
  • 返回值rejected
Promise.reject(1) // rejected 1

withResolvers

  • 语法Promise.withResolvers()
  • 返回值{ promise, resolve, reject }
let { promise, resolve, reject } = Promise.withResolvers()
resolve(1)
promise // resolved 1

Instance Methods

then

  • 描述:为 promise 注册 fulfilled 和 rejected 时的回调
  • 语法then(onFulfilled?, onRejected?)
  • 参数
    • onFulfilled = x => x:fulfilled 时的回调
    • onRejected = x => { throw x }:rejected 时的回调
Promise.resolve(1).then(
    val => { console.log('ok ' + val) },
    val => { console.log('error ' + val) }
) // ok 1

catch

  • 描述:为 promise 注册 rejected 时的回调
  • 语法catch(onRejected?)
  • 参数
    • onRejected = x => { throw x }:rejected 时的回调
Promise.reject(1).catch(
    val => { console.log('error ' + val) }
) // error 1

finally

  • 描述:为 promise 注册 settled 时的回调
  • 语法finally(onFinally?)
  • 参数
    • onFinally = x => x:settled 时的回调
Promise.resolve(1).finally(
    () => { console.log('finally') }
) // finally
 
Promise.reject(1).finally(
    () => { console.log('finally') }
) // finally