then
then
函数能够return
另外一个promise
:数组
const p1 = new Promise((resolve, reject) =>{
resolve('p1')
})
const p2 = new Promise((resolve, reject) =>{
setTimeout(() =>{
resolve('p2')
},3000)
})
p1.then(res => {
console.log(res)
return p2
}).then(res =>{
// p2 resolve后才执行
console.log(res)
})
//p1
// 3s后输出...
// p2
复制代码
那么这个p2
就会代替当前p1
的状态,等到新的p2
的状态修改时,下一个then
才会执行promise
catch
能够捕获到promise
程序执行中的error
,等同于 .then(null, rejection)
或 .then(undefined, rejection)
函数
promise
函数体中抛出的error
。在promise
resolve
后,再抛出错误,不会被捕获const p1 = new Promise((resolve,reject) => {throw new Error('error')})
p1.catch(error => console.log(error)) // Error: error
复制代码
promise
的reject
操做const p2 = new Promise((resolve,reject) => reject('rejected'))
p2.catch(error => console.log(error)) // rejected
复制代码
then
函数体中抛出的error
const p3 = new Promise((resolve,reject) => resolve('resolved'))
p3.then(res =>{
throw new Error('error')
}).catch(error => console.log(error)) // Error: error
复制代码
then
函数能够返回一个promise
(若是没有定义catch方法),若是这个promise
函数体中有reject
或者error
,也能够捕获到catch
方式捕获错误,而不是then
的第二个参数:由于catch
能够捕获到它前面全部then
方法中的错误ui
finally
promise
最后状态如何,都会执行的操做promise
最后的状态Promise.all
Iterator
接口的对象均可以。promise
实例,若是不是,就会调用Promise.resolve
转换为Promise
实例const obj = {
[Symbol.iterator]() {
let index = 0
return {
next() {
return {
// promise对象 和 其余类型均可以
value: new Promise(resolve => resolve(index++)), done: index > 2
// value: index++, done: index > 2
}
}
}
}
}
const p = Promise.all(obj)
p.then(res => {
console.log(res) // [0, 1]
})
复制代码
const p = Promise.all([p1, p2, p3]);
复制代码
p的状态由p一、p二、p3决定,分红两种状况:spa
p一、p二、p3
的状态都变成fulfilled
,p的状态才会变成fulfilled
,此时p一、p二、p3的返回值组成一个数组,传递给p的回调函数。p一、p二、p3
之中有一个被rejected
,p的状态就变成rejected
,此时第一个被reject
的实例的返回值,会传递给p的回调函数。catch
若是参数中的promise
定义了catch
方法,那么Promise.all()
的catch
就不会捕获到错误code
Promise.race
Promise
实例的返回值,就传递给p的回调函数。catch
规则同Promise.all
Promise.resolve
将现有对象转为
Promise
对象。对象
promise
实例:原封不动的返回这个实例。thenable
对象:将它转为promise
对象,而后当即执行它的then
方法thenable
对象,或者是一个原始值:返回一个新的promise
对象,状态为resolved
resolved
状态的promise
对象返回一个状态为
rejected
的promise
实例接口
Promise.reject()
方法的参数,会原封不动地做为reject的理由,变成后续方法的参数回调函数
const thenable = {
then(resolve, reject) {
reject('error');
}
};
Promise.reject(thenable)
.catch(e => {
console.log(e === thenable)
})
// true e并非'error'
复制代码