Promise的then和catch如何影响状态的变化
记住两句话:
1.then正常返回resolved,里面有报错返回reject
1 const p1 = Promise.resolve().then(()=>{ 2 console.log(123) 3 }) 4 5 console.log('p1',p1) //此时的状态是resolve,后面可以跟then
6 const p2 = Promise.resolve().then(()=>{
8 throw new error('then error')
9 })
11 console.log('p2',p2) //此时的状态是reject,后面可以跟Catch
2.catch正常返回resolved,里面有报错返回reject
1 const p3 = Promise.reject().catch(()=>{ 2 console.log(123) 3 }) 4 5 console.log('p3',p3) //此时的状态是resolve,后面可以跟then 6 7 const p4 = Promise.reject().catch(()=>{ 8 throw new error('then error') 9 }) 10 11 console.log('p4',p4) //此时的状态是reject,后面可以跟catch
面试题
Promise.resolve().then(()=>{ console.log(1) }).catch(()=>{ console.log(2) }).then(()=>{ console.log(3) }) //因为then没有抛错所以答案是1,3,后面catch不会执行 Promise.resolve().then(()=>{ console.log(1) throw new error('then err') }).catch(()=>{ console.log(2) }).then(()=>{ console.log(3) }) //因为then抛错所以答案是1,2,3 Promise.resolve().then(()=>{ console.log(1) throw new error('then err') }).catch(()=>{ console.log(2) }).catch(()=>{ console.log(3) }) //因为then抛错,第一个catch没有跑错,所以答案是1,2
                    
                
                
            
        
浙公网安备 33010602011771号