async await 的语法可以让非同步的程序码看起来像同步一样。
例如:
async function test(){
return new Promise((resolve,reject) => {
reject("test")
})
}
let res = test();
console.log(res);
将上面的例子加入 await 以及 try catch:
async function test(){
let testPromise = new Promise((resolve,reject) => {
reject("test")
})
try{
let res = await testPromise;
console.log(testPromise);
}catch(e){
console.log(e);
console.log(testPromise);
}
}
test();
await 右边的 testPromise 结果为 reject,所以会进到 catch 区块
再举个非同步的例子:
function test(){
setTimeout(function() {
throw new Error("Error!!!")
}, 0);
}
try{
test()
console.log("成功")
}catch(e){
console.log("失败")
console.log(e)
}
上面的 test() 里有 setTimeout function,且里面写了 throw Error(),理论上 JavaScript 看到 throw 就要执行 catch 区块的程序码了,但因为 setTimeout 是非同步,JavaScript 会先略过它,先往下执行,往下进到 try 区块里,所以最终结果显示:成功。
要处理这样的问题,就要派上 async await 了。
改写後的程序码如下:
await 右边的要是 Promise,所以将 setTimeout 放到一个 Promise object 中
async function test() {
let newFunc = new Promise((resolve,reject) => {
setTimeout(function () {
reject("Error!!!");
}, 0);
})
try{
let res = await newFunc;
console.log(res);
console.log("成功");
}catch(e){
console.log(e);
console.log("失败");
}
}
test()
// Error!!!
// 失败
参考资料:
https://medium.com/unalai/%E8%AA%8D%E8%AD%98-try-catch-%E8%99%95%E7%90%86%E9%8C%AF%E8%AA%A4-f262d5690820
https://blog.csdn.net/lyyrhf/article/details/115338763
<<: [Python 爬虫这样学,一定是大拇指拉!] DAY12 - HTTP / HTTPS (3)
Day 20 - Android Studio的EditText的基本使用 上一篇我们讲到了网路So...
撰写程序的时候,几乎都是用let去撰写,只知道他比var还要安全,不容易出错,更详细的原因,就没办法...
前言 铁人赛最後一日,直到此我们已经学习了许多知识、也了解了不少 PVE 的操作!最後一天就来聊聊之...
昨天我们已经讲了 Powershell 的逻辑运算,今天我们就来看看,Powershell 的逻辑判...
=x= 🌵 NEWS 前台 View 页面後端功能制作。 NEWS View 页面资料介绍 : 📌 ...