promise的状态
- pending
- resolved
- rejected
三种状态之间的关系
pending——>resolved
pending——>rejected
resolved 不能转换为 rejected
触发的回调函数
resolved状态触发的是then回调
rejected状态触发的是catch回调
pending状态不会触发then 和catch 回调
catch 和 then
then正常执行返回的是resolved状态,如果then方法中有报错,返回的则是rejected状态catch正常执行返回的是resolved状态,如果catch方法中有报错,返回的则是rejected状态
代码验证
第一段代码:
// Promise.resolve()——>resolved,所以会触发then回调
Promise.resolve().then(() => {
console.log(1);
//内部没有报错,then方法会返回一个resolved状态的promise对象
}).catch(() => {
console.log(2)
}).then(() => { // resolved状态会触发then回调
console.log(3)
})
输出结果: 1 3
第二段代码:
// Promise.resolve()——>resolved,所以会触发then回调
Promise.resolve().then(() => {
console.log(1)
throw new Error('erro1')
// 返回 rejected 状态的 promise
}).catch(() => {
console.log(2)
// 返回 resolved 状态的 promise
}).then(() => {
console.log(3)
})
输出结果: 1 2 3
第三段代码:
// Promise.resolve()——>resolved,所以会触发then回调
Promise.resolve().then(() => {
console.log(1)
throw new Error('erro1')
// 返回 rejected 状态的 promise
}).catch(() => {
console.log(2)
// 返回 resolved 状态的 promise
}).catch(() => {
console.log(3)
})
输出结果: 1 2