async 從字面上看就是“異步”,它放在函數定義之前,是使該函數在調用時開一個子線程,以不影響主線程的運行。
而 await 經常和 async 組合使用,在 async 定義的函數中來等待需要時間運行的代碼(如ajax請求、Promise對象)的運行結果,以做后續的處理。
??如下面的返回Promise對象的函數:
function print(delay, message) {
return new Promise(function (resolve, reject) { // 返回Promise對象
setTimeout(function () { // 延遲執行函數
console.log(message);
resolve();
}, delay);
});
}
如果需要運行通過,就需要經過then、catch、finally函數來執行響應的代碼:
print(1000, "First").then(function () { // 1秒之后輸出“First”
return print(2000, "Second"); // 2秒之后輸出“Second”
}).then(function () {
return print(1000, "Third"); // 1秒之后輸出“Third”
}).then(function (){
print(2000, "Fourth"); // 2秒之后輸出“Fourth”
});
??而使用 async/await 可以實現同樣的效果,使用異步操作就像同步操作一樣簡單:
async function asyncFunc() {
await print(1000, "First");
await print(2000, "Second");
await print(1000, "Third");
await print(2000, "Fourth");
}
asyncFunc();
??而對于 Promise 中的異常處理,使用 try-catch 來實現:
async function asyncFunc() {
try {
await print(1000, "First"); //1秒后輸出"First"
});
} catch (err) {
console.log(err); //輸出異常錯誤
}
try {
await print(2000, "Second"); //2秒后輸出"Second"
});
} catch (err) {
console.log(err); //輸出異常錯誤
}
try {
await print(1000, "Third"); //1秒后輸出"Third"
});
} catch (err) {
console.log(err); //輸出異常錯誤
}
try {
await print(2000, "Fourth"); //2秒后輸出"Fourd"
});
} catch (err) {
console.log(err); //輸出異常錯誤
}
}
asyncFunc();
浙公網安備 33010602011771號