谢邀: )
理解上本没有错,但是可以再细分一些 对于一个Promise对象
有三种状态:pending(未完成)、fulfilled(完成)、rejected(拒绝)
有两种过度:pending -> fulfilled 或者是 pending -> rejected
对于Promise异步编程来说
对象的状态一旦改变,就不能在变,而且对象的状态不会受到外界的影响
在Promise实例中
如果状态变为fulfilled,则可以返回resolve函数,然后作为参数传递到then中的成功处理函数中
如果状态变为rejected,则可以返回reject函数,然后作为参数传递到then中的拒绝处理函数中
而在then方法中,没有JS引擎部署好的resolve和reject函数
所以在then方法中可以通过返回值,创建新的Promise对象之后
将返回值传递到下一个then方法的成功或拒绝处理函数中
如果没有返回值,则默认为undefined
Promise.reject('a error')
.then(res => console.log(res), err => console.log(err))
.then(res => console.log(res), err => console.log(err));
这里其实很好理解,第一个then方法中
提供了成功处理函数(fulfill)和拒绝处理函数(reject)来处理Promise.reject函数的值
此时会将结果传递给reject函数处理
由于在then方法中已经捕获错误了,所以错误就不会继续传递到下一个then方法中
也就是说在下一个then方法中执行成功处理函数
而不是执行错误处理函数
所以打印的结果是 'a error', undefined
Promise.reject('a error')
.then(res => console.log(res),
err => {
console.log(err)
return 123
}
)
.then(res => console.log(res), err => console.log(err))
假设code变成这样,会输出'a error', 123
上面其实有提到在then方法会创建一个新的Promise实例
通过返回值将结果传递下去
如果没有返回值,则默认返回undefined
Promise.reject('a error')
.then(res => console.log(res))
.then(res => console.log(res), err => console.log(err))
假设code变成这样,此时会输出'a error'
第一个then方法中没有捕获到错误
但是在then方法中会有一个默认的拒绝处理函数
函数体内会继续抛出一个错误
然后将错误延续到下一个then方法中捕获
Promise.reject('a error')
.then(res => console.log(res),
// 默认的错误处理函数
err => throw err
)
.then(res => console.log(res),
// 捕获上一个then方法传递下来的err
err => console.log(err)
);
总的来说呢,就是Promise对于错误处理机制的理解
如果错误已经捕获了,那么错误不会继续传递下去
如果错误没有被捕获,那么错误会隐式传递下去,直到有错误处理函数来捕获这个错误