初識
async 函式表示這個函式內部有異步請求,如果這個 async 函式沒有回傳值,那么這個 async 僅僅只是一個標識而已.
await 需要結合 async 函式一起使用,它通常用于等待一個 Promise 函式或 async 函式的執行(你當然可以寫個await 123,但這不會有任何作用)
先看代碼
console.log(1);
(async function () {
console.log(2);
const res = await req(); // 隨意定義一個回傳值是Promise的函式
console.log(3);
if (res[0]) {
throw new Error(res[0]);
} else {
console.log("請求成功");
}
})();
console.log(4);
如果對 Promise 很了解的話,應該很快能看出控制臺的輸出順序是 1 2 4 3 "請求成功",如果你判斷錯誤了也沒關系,實際開發中多用用就熟悉了.筆者也經常會判斷失誤.
進階
上面說到 async 函式如果沒有回傳值則這僅僅只是一個標識,那么如果有回傳值呢?
async function get() {
return 123;
}
const f = get(); // Promise { 123 }
上面代碼可以看出 async 函式回傳了一個 Promise 物件.
作用就是你可以不用再在一個函式里手寫return new Promise((resolve, reject)=>{})了,可以直接回傳一個 async 函式
要注意的是在 Promise 中是使用resolve()回傳正常值,reject()回傳例外值
在 async函式 中使用return回傳正常值,使用拋出錯誤throw new Error()回傳例外值
function (a,b) {
return async function () {
const res = await getSomething({a,b});
if (res.code === 200) {
return [res.data.rows];
} else {
throw new Error(res.msg);
}
};
}
處理例外
拋出錯誤那勢必就要處理錯誤.而處理錯誤的方式也是有好幾種的,我只在這里寫我推薦的 Error First 思想, 另一個方法是傳統的 try catch
async function sendReq() {
const res = await getSomething().then((res) => [null, res]).catch((error) => [error, null]);
if (res[0] !== null) {
// 錯誤邏輯
console.error(error);
return;
}
// 正確邏輯
console.log(res[1]);
}
上面的代碼,在 await 函式后面加上.then().catch(),在學習Promise的時候,我們知道Promise的then方法是處理resolve,then后的catch方法是處理reject,并且這兩個也都會回傳一個Promise,因此再使用await接收then或catch回傳的Promise即可.
回傳的值為一個陣列,發生錯誤的時候把錯誤放到陣列的第一位,這種思想稱之為Error First思想.很方便判斷是否出錯.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/413101.html
標籤:其他
上一篇:ES6常用陣列方法及模擬實作
