站長資訊網
        最全最豐富的資訊網站

        理解JavaScript之Async/Await的新語法

        理解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。

        贊(0)
        分享到: 更多 (0)
        網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
        主站蜘蛛池模板: 日韩精品一区二区三区不卡| 亚洲精品国产成人影院| 精品福利一区二区三区精品国产第一国产综合精品 | 中文字幕乱码中文乱码51精品| 欧美一区二区精品系列在线观看| 亚洲精品国产品国语在线| 国产精品午夜免费观看网站| 91国内外精品自在线播放| 中文字幕精品无码一区二区| 国产精品亚洲视频| 欧美精品国产精品| 国产精品99久久免费观看| 亚洲精品亚洲人成在线观看下载| 国产亚洲精品高清在线| 亚洲国产精品成| 国产成人精品日本亚洲专| 国产最新进精品视频| 人人妻人人澡人人爽人人精品电影| 日本精品久久久久久久久免费| 国产精品亚洲美女久久久| 99热都是精品久久久久久| 久久精品国产99国产精偷| 69SEX久久精品国产麻豆| 四虎国产精品永久在线| 亚洲精品乱码久久久久久| 四虎精品免费永久免费视频| 精品伦精品一区二区三区视频| 国产成人久久久精品二区三区| 思思99热在线观看精品| 日韩精品久久久久久| 色花堂国产精品第一页| 2021国产成人精品久久| 99精品欧美一区二区三区| 影视网欧洲精品| 高清日韩精品一区二区三区| 91精品婷婷国产综合久久| 91久久精品国产成人久久| www.日韩精品| 久久精品夜色噜噜亚洲A∨| 欧美精品福利在线视频 | 欧美激情精品久久久久|