async 与 await
- 作用: 能帮助我们把 异步代码, 写的和 同步代码一样
function fn(){
const p = new Promise(function(def, res){
const timer = Math.floor(Math.random() * 3000) + 1500
setTimeout(()=>{
if(timer> 3000){
res('网络申请失败,请重新申请')
}else{
def('申请成功,欢迎访问')
}
},timer)
})
return p
}
async function fun(){
let res1 = await fn()
}
fun()
async/await 的问题
- 没有办法捕获到 错误, 只能接受 promise 的成功状态
- 如果报错, 会中断程序执行
async/await 的问题 的 解决方法1: try...catch
- 首次执行的时候 会走 try 这个分支, 如果这个位置有报错
- 他会结束执行 try 分支, 然后走 catch 分支
- 如果再运行 try 分支的时候, 没有报错, 那么 catch 不会运行
async function fun (){
try{
let r1 = await fn()
console.log(r1)
}catch(error){
console.log(error)
console.log('如果失败了,就会执行这行代码')
}
}
fun()