promise處理回調以及Async/Await替代promise的六大理由

簡要介紹:ES6中,可以通過promise來處理回調函數,回調函數經常用於異步操作中,間接來說,可以通過promise優化異步操作。

1.什麼是JS中的回調函數?

回調函數是作爲參數傳遞給另外一個函數,並且該回調函數在函數主體執行完後再執行。

2.常見的回調函數以及存在的缺陷

常見的回調函數:
我們在jquery的ajax請求中,可以看到回調的身影,經典的封裝後的ajax請求就是一個,success後面所跟的函數就是一個回調函數。
存在的問題:
因爲JS是同步的,通過回調函數異步操作,會造成回調函數的嵌套,很影響代碼的可讀性。

3.promise處理回調嵌套

(1)什麼是promise

promise通常用於處理函數的異步調用,通過鏈式調用的方式,使得代碼更加直觀,舉例來說:

var myPromise=function(tag){

  return new Promise(function(resolve,reject){
    if(tag){
      resolve('默認參數success');
    }else{
      reject('默認參數filed');
    }
})
}
myPromise(true).then(function(message){
  console.log(message)
})  //"輸出默認參數success"

我們可以看到設置promise只要new Promise()就可以,並且接受一個函數,該函數裏面會執行resolve()方法,表示異步調用成功時執行,reject()表示異步調用失敗時候調用。

在鏈式調用時候,then後面接的第一個函數爲成功之時調用的函數—resolve,並且這裏的默認參數等同於promise中resolve中的初始參數。

(2)then和catch

then:可以在promise中實現鏈式調用,在上文中已經介紹。補充,then裏面的第二個函數,爲異步調用失敗之時執行,接上面的例子:

myPromise(false).then(null,function(err){
  console.log(err)
})
//這樣會輸出"默認參數filed"

catch:catch方法,相當於then(null,function(err){console.log(err)}失敗方法調用的一個縮寫。

myPromise(false).catch(function(err){console.log(err)})
//這句話與上面等價,也會輸出"默認參數filed"
(3)Promise.all

Promise.all 可以接收一個元素爲 Promise 對象的數組作爲參數,當這個數組裏面所有的 Promise 對象都變爲 resolve 時,該方法纔會返回。

var p1 = new Promise(function (resolve) {
    setTimeout(function () {
        resolve("Hello");
    }, 3000);
});

var p2 = new Promise(function (resolve) {
    setTimeout(function () {
        resolve("World");
    }, 1000);
});

Promise.all([p1, p2]).then(function (result) {
    console.log(result); // ["Hello", "World"]
});

4.爲什麼Async/Await比promise更好?

1.簡潔

使用Promise是這樣的:
getJSON函數返回一個promise,這個promise成功resolve時會返回一個json對象。我們只是調用這個函數,打印返回的JSON對象,然後返回”done”。

const makeRequest = () =>
  getJSON()
    .then(data => {
      console.log(data)
      return "done"
    })

makeRequest()

使用Async/Await是這樣的:

const makeRequest = async () => {
  console.log(await getJSON())
  return "done"
}

makeRequest()

函數前面多了一個aync關鍵字。await關鍵字只能用在aync定義的函數內。async函數會隱式地返回一個promise,該promise的reosolve值就是函數return的值。(示例中reosolve值就是字符串”done”)。await getJSON()表示console.log會等到getJSON的promise成功reosolve之後再執行。

2. 錯誤處理

Async/Await讓try/catch可以同時處理同步和異步錯誤。在下面的promise示例中,try/catch不能處理JSON.parse的錯誤,因爲它在Promise中。我們需要使用.catch,這樣錯誤處理代碼非常冗餘。並且,在我們的實際生產代碼會更加複雜。

const makeRequest = () => {
  try {
    getJSON()
      .then(result => {
        // JSON.parse可能會出錯
        const data = JSON.parse(result)
        console.log(data)
      })
      // 取消註釋,處理異步代碼的錯誤
      // .catch((err) => {
      //   console.log(err)
      // })
  } catch (err) {
    console.log(err)
  }
}

使用aync/await的話,catch能處理JSON.parse錯誤:

const makeRequest = async () => {
  try {
    // this parse may fail
    const data = JSON.parse(await getJSON())
    console.log(data)
  } catch (err) {
    console.log(err)
  }
}
3. 條件語句

下面實例中,通過判斷返回數據來決定是直接返回,還是繼續獲取更多的數據。

const makeRequest = () => {
  return getJSON()
    .then(data => {
      if (data.needsAnotherRequest) {
        return makeAnotherRequest(data)
          .then(moreData => {
            console.log(moreData)
            return moreData
          })
      } else {
        console.log(data)
        return data
      }
    })
}

這些代碼看着就頭痛。嵌套(6層),括號,return語句很容易讓人感到迷茫,而它們只是需要將最終結果傳遞到最外層的Promise。

上面的代碼使用async/await編寫可以大大地提高可讀性:

const makeRequest = async () => {
  const data = await getJSON()
  if (data.needsAnotherRequest) {
    const moreData = await makeAnotherRequest(data);
    console.log(moreData)
    return moreData
  } else {
    console.log(data)
    return data    
  }
}
4.中間值

你很可能遇到過這樣的場景,調用promise1,使用promise1返回的結果去調用promise2,然後使用兩者的結果去調用promise3。你的代碼很可能是這樣的:

const makeRequest = () => {
  return promise1()
    .then(value1 => {
      return promise2(value1)
        .then(value2 => {        
          return promise3(value1, value2)
        })
    })
}

如果promise3不需要value1,可以很簡單地將promise嵌套鋪平。如果你忍受不了嵌套,你可以將value 1 & 2 放進Promise.all來避免深層嵌套:

const makeRequest = () => {
  return promise1()
    .then(value1 => {
      return Promise.all([value1, promise2(value1)])
    })
    .then(([value1, value2]) => {      
      return promise3(value1, value2)
    })
}

這種方法爲了可讀性犧牲了語義。除了避免嵌套,並沒有其他理由將value1和value2放在一個數組中。

使用async/await的話,代碼會變得異常簡單和直觀。

const makeRequest = async () => {
  const value1 = await promise1()
  const value2 = await promise2(value1)
  return promise3(value1, value2)
}
5.錯誤棧

下面示例中調用了多個Promise,假設Promise鏈中某個地方拋出了一個錯誤:

const makeRequest = () => {
  return callAPromise()
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => {
      throw new Error("oops");
    })
}

makeRequest()
  .catch(err => {
    console.log(err);
    // output
    // Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
  })

Promise鏈中返回的錯誤棧沒有給出錯誤發生位置的線索。更糟糕的是,它會誤導我們;錯誤棧中唯一的函數名爲callAPromise,然而它和錯誤沒有關係。(文件名和行號還是有用的)。

然而,async/await中的錯誤棧會指向錯誤所在的函數:

const makeRequest = async () => {
  await callAPromise()
  await callAPromise()
  await callAPromise()
  await callAPromise()
  await callAPromise()
  throw new Error("oops");
}

makeRequest()
  .catch(err => {
    console.log(err);
    // output
    // Error: oops at makeRequest (index.js:7:9)
  })

在開發環境中,這一點優勢並不大。但是,當你分析生產環境的錯誤日誌時,它將非常有用。這時,知道錯誤發生在makeRequest比知道錯誤發生在then鏈中要好。

6.調試

最後一點,也是非常重要的一點在於,async/await能夠使得代碼調試更簡單。2個理由使得調試Promise變得非常痛苦:

  • 不能在返回表達式的箭頭函數中設置斷點
    這裏寫圖片描述
    如果你在.then代碼塊中設置斷點,使用Step Over快捷鍵,調試器不會跳到下一個.then,因爲它只會跳過異步代碼。

  • 使用await/async時,你不再需要那麼多箭頭函數,這樣你就可以像調試同步代碼一樣跳過await語句。
    這裏寫圖片描述

結論

Async/Await是近年來JavaScript添加的最革命性的的特性之一。它會讓你發現Promise的語法有多糟糕,而且提供了一個直觀的替代方法。

憂慮

對於Async/Await,也許你有一些合理的懷疑:

它使得異步代碼不再明顯: 我們已經習慣了用回調函數或者.then來識別異步代碼,我們可能需要花數個星期去習慣新的標誌。但是,C#擁有這個特性已經很多年了,熟悉它的朋友應該知道暫時的稍微不方便是值得的。
Node 7不是LTS(長期支持版本): 但是,Node 8下個月就會發布,將代碼遷移到新版本會非常簡單。

參考:
1.https://cnodejs.org/topic/58e4914e43ee7e7106c13541
2.https://blog.csdn.net/liwusen/article/details/54142748

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章