首頁 > web前端 > js教程 > 主體

理解JavaScript之Async/Await的新語法

coldplay.xixi
發布: 2020-07-08 16:31:41
轉載
2117 人瀏覽過

理解JavaScript之Async/Await的新語法

受到Zeit團隊部落格文章的啟發,我們的PayPal團隊在不久之前將伺服器端資料庫遷移到了Async/Await。我想要和你們分享我的經驗。

首先我們先來了解兩個名詞:

  • Async函數
  • ##Await 關鍵字
你們總是把Async和Await放在一起說,但是你需要知道的是,它們是兩個不同的東西。對於Async函數和Await關鍵字,你需要了解的是,他們從某種程度上來說當然是有一定關聯的,但是在沒有Await的情況下,Async函數依然可以使用。

相關學習推薦:

javascript影片教學

#函數會傳回一個Promise

當你用async關鍵字建立一個函數的時候,這個函數永遠都會回傳一個Promise。當你在async函數內部進行回傳的時候,它會用一個Promise包裹你的值。

 // here is an async function
 async function getNumber() {

  return 4 // actually returns a Promise
  }
  // the same function using promises
  function getNumber() {

     return Promise.resolve(4)

}
登入後複製

Async函數和它的基於Promise的Equivalent

除了將你的return轉換為Promise之外,async函數還有一個特別之處,那就是它是唯一一個讓你使用await關鍵字的地方。

Await讓你可以暫停async函數的執行,直到它受到了一個promise的結果。這讓你可以寫出依照執行順序顯示的async程式碼。

 // async function to show user data
 async function displayUserData() {

    let me = await fetch('/users/me')

    console.log(me)

}// promise-based equivalent
function displayUserData() {

    return fetch('/users/me').then(function(me) {

        console.log(me)

    })

})
登入後複製

Await允許你在不需要callback的情況下寫非同步程式碼。這樣做的好處是讓你的程式碼可讀性更高。而且await可以與任何promise相容,而不僅僅是用async函數創建的promise。

在Async函數中處理錯誤

因為async函數也是一個Promise,當你在程式碼中放入一個async函數的時候,它會被吸收,然後作為rejected Promise被返回。

 // basic error handling with async functions
 async function getData(param) {

   if (isBad(param)) {     
    throw new Error("this is a bad param")

   }   
   // ...
   }
   // basic promise-based error handling example
   function getData(param) {

   if (isBad(param)) {      
   return Promise.reject(new Error("this is a bad param"))

   }  
    // ...
    }
登入後複製

當你使用await呼叫Promise的時候,你可以用

try/catch將其包裹,或是你需要在回傳的Promise中加入一個catch handler。

 // rely on try/catch around the awaited Promise

async function doSomething() {   
 try {       
  let data = await getData()

    } catch (err) {       
     console.error(err)

    }

}
// add a catch handlerfunction doSomething() {    
return getData().catch(err => {      
  console.error(err)

    })

}
登入後複製

整合

利用好promise的錯誤處理屬性,以及async函數的簡潔語法,能夠帶給你一些強大的能力。

在下面這個簡單的例子中,你會看到我是如何利用async函數內在的錯誤處理能力的,它讓我簡化了Express應用程式中的錯誤處理流程。

 // catch any errors in the promise and either forward them to next(err) or ignore them
 const catchErrors = fn => (req, res, next) => fn(req, res, next).catch(next)
 const ignoreErrors = fn => (req, res, next) => fn(req, res, next).catch(() => next())
 // wrap my routes in those helpers functions to get error handling
 app.get('/sendMoney/:amount', catchErrors(sendMoney))
 // use our ignoreErrors helper to ignore any errors in the logging middleware
 app.get('/doSomethingElse', ignoreErrors(logSomething), doSomethingElse)
 // controller method can throw errors knowing router will pick it up
 export async function sendMoney(req, res, next) {  
 if (!req.param.amount) {     
 throw new Error('You need to provide an amount!')  

  }  await Money.sendPayment(amount) // no try/catch needed

  res.send(`You just sent ${amount}`)}

// basic async logging middleware
export async function logSomething(req, res, next) {

    // ...    
    throw new Error('Something went wrong with your logging')

    // ...

}
登入後複製

之前,我們一直都在用

next(err)來處理錯誤。然而,有了async/await,我們可以將錯誤放在程式碼中的任何位置,然後router會將這些錯誤throw到Express提供的next函數中,這樣就極大的簡化了錯誤處理流程。

我花了幾個小時的時間對資料庫進行了遷移。要用這個方式,你唯一需要的,就是對Promise的深刻理解,以及學會如何設定babel。

以上是理解JavaScript之Async/Await的新語法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:webhek.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!