promise的三种状态
三种状态
pending准备 fulfilled成功 rejected失败
pengding->fulfilled/pending->rejected
- 变化是不可逆的
pending准备, 不会触发then和catch



promise then和catch如何影响状态的转换
then正常返回resolved,里面有报错则返回rejected
const p1 = Promise.resolve().then(() => {
return 100
})
p1.then(() => {
console.log('123')
})
const p1 = Promise.resolve().then(() => {
throw new Error('then error')
})
p1.then(() => {
console.log('456')
}).catch(() => {
console.error('err100', err)
})
catch正常返回resolved,里面有报错则返回rejected
const p3 = Promise.reject('my error').catch((err) => {
console.error(err)
})
p3.then(() => {
console.log('123')
})
const p4 = Promise.reject('my error').catch((err) => {
throw new Error('catch error')
})
p1.then(() => {
console.log('456')
}).catch(() => {
console.error('err100', err)
})
面试题
Promise.resolve().then(() => {
console.log(1)
}).catch(() => {
console.log(2)
}).then(() => {
console.log(3)
})
1
3
Promise.resolve().then(() => {
console.log(1)
throw new Error('erro1')
}).catch(() => {
console.log(2)
}).then(() => {
console.log(3)
})
1
2
3
Promise.resolve().then(() => {
console.log(1)
throw new Error('erro1')
}).catch(() => {
console.log(2)
}).catch(() => {
console.log(3)
})
1
2