1- then
# then 之后返回的 Promise的状态是fullfilled 如果遇到错误,状态会变为 rejected# then 只能触发promise-->fullfilled的状态
var p = Promise.resolve(100).then((res)=>{ console.log(res)})console.log(p) // resolvedvar p = Promise.resolve(100).then((res)=>{ console.log(res) throw "err"})console.log(p) // reject状态var p = Promise.resolve(100).then((res)=>{ console.log(res) throw "err"})p.then(()=>{ // 报错了 console.log(200)})
2- catch
catch 之后返回的promise的状态 正常情况下是 fullfilled ,如果有错误,状态为reject
var p = Promise.reject(100).catch(res=>{ console.log(res)})console.log(p) // fullfilled 状态var p = Promise.reject(100).catch(res=>{ console.log(res) throw "err"})console.log(p) // rejected状态
3- 总结 练习
then catch1.得到的结果都是Promise2.正常情况下状态都是fullfilled,遇到错误状态为rejected
var p = Promise.reject(100).catch(res=>{ console.log(res)})p.catch(()=>{ console.log(200)}).then(()=>{ console.log(300)}).catch(()=>{ console.log(400)})// 100 300var p = Promise.reject(100).catch(res=>{ console.log(res)})p.catch(()=>{ console.log(200)}).then(()=>{ console.log(300) throw "err"}).catch(()=>{ console.log(400)}).then(()=>{ console.log(500)})// 100 300 400 500
4- async-await中的错误处理
await 只能得到Promise--resolved状态的结果,作用相当于 then 函数
(async ()=>{ var p = Promise.reject("err") try{ let res = await p console.log(res) }catch(err){ console.log(err) }})()