1. 程式人生 > 其它 >建議收藏:async 與 await的理解 ,淺析 promise 的理解

建議收藏:async 與 await的理解 ,淺析 promise 的理解

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 函式返回了一個 Promise 物件.

async function get() {
    return 123;
}
const f = get(); // Promise { 123 }

f是一個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思想.很方便判斷是否出錯.