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