深入理解promise的三种状态与链式调用pending/reslove/reject

promise出现的目的一为处理JavaScript里的异步,再就是避免回调地狱。

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)
})

 

posted @ 2021-03-01 10:29  JackieDYH  阅读(33)  评论(0)    收藏  举报  来源