关于promise:Promise三种状态

三种状态

1.pending:在过程中还没有后果
2.resolved:胜利
3.rejected:失败

状态变动

1、pending -> resolved
2、pending -> rejected

状态的体现

pending状态不会触发then和catch
resolved状态会触发后续的then回调函数
rejected状态会触发后续的catch回调函数

then和catch扭转状态

then失常状况下会返回resolved,报错则返回rejected
catch失常状况下会返回resolved,报错则返回rejected

测试题

//第一题(后果会打印进去1,3,返回resolved状态)
Promise.resolve().then(()=>{
    console.log(1) //1  resolved
}).catch(()=>{
    console.log(2)
}).then(()=>{
    console.log(3) // 3 resolved
})

//第二题(后果会打印进去1,2,3)
Promise.resolve().then(()=>{
    console.log(1) //1 
    throw  new Error("error1") //rejected
}).catch(()=>{
    console.log(2) //2 resolved
}).then(()=>{
    console.log(3) //3 resolved
})

//第三题(后果会打印进去1,2)
Promise.resolve.then(()=>{
    console.log(1) //1
    throw new Error("error1") //rejected
}).catch(()=>{
    console.log(2) //2 resolved
}).catch(()=>{
    console.log(3)
})

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理