Promise
Constructor
Promise
- 描述:封装一个 Promise
- 语法:
new Promise(executor)
- 参数
executor(resolve?, reject?)
:构造函数resolve
:兑现一个 promisereject
:拒绝一个 promise
let p = new Promise((resolve, reject) => {
resolve(1)
}) // fulfilled 1
Static Methods
all
- 语法:
Promise.all(iterable)
- 返回值
fulfilled
:所有 promise fulfilledrejected
:任意 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 fulfilledrejected
:所有 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 fulfilledrejected
:任意 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