亚洲最大看欧美片,亚洲图揄拍自拍另类图片,欧美精品v国产精品v呦,日本在线精品视频免费

  • 站長資訊網(wǎng)
    最全最豐富的資訊網(wǎng)站

    理解JavaScript之Async/Await的新語法

    理解JavaScript之Async/Await的新語法

    受到Zeit團(tuán)隊(duì)博文的啟發(fā),我們的PayPal團(tuán)隊(duì)不久之前將服務(wù)器端數(shù)據(jù)庫遷移到了Async/Await上。我想要和你們分享一下我的經(jīng)驗(yàn)。

    首先我們先來了解兩個術(shù)語:

    • Async函數(shù)
    • Await 關(guān)鍵詞

    你們總是將Async和Await放在一起說,但是你需要知道的是,它們是兩個不同的東西。對于Async函數(shù)和Await關(guān)鍵詞,你需要了解的是,他們從某種程度上來說當(dāng)然是有一定關(guān)聯(lián)的,但是在沒有Await的情況下,Async函數(shù)依然可以使用。

    相關(guān)學(xué)習(xí)推薦:javascript視頻教程

    函數(shù)會返回一個Promise

    當(dāng)你用async關(guān)鍵詞創(chuàng)建一個函數(shù)的時(shí)候,這個函數(shù)永遠(yuǎn)都會返回一個Promise。當(dāng)你在async函數(shù)內(nèi)部進(jìn)行返回的時(shí)候,它會用一個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函數(shù)和它的基于Promise的Equivalent

    除了將你的return轉(zhuǎn)換為Promise之外,async函數(shù)還有一個特別之處,那就是它是唯一一個讓你使用await關(guān)鍵詞的地方。

    Await讓你可以暫停async函數(shù)的執(zhí)行,直到它受到了一個promise的結(jié)果。這讓你可以寫出按照執(zhí)行順序顯示的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函數(shù)所創(chuàng)建的promise。

    在Async函數(shù)中處理錯誤

    因?yàn)閍sync函數(shù)也是一個Promise,當(dāng)你在代碼中放入一個async函數(shù)的時(shí)候,它會被吸收,然后作為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"))     }       // ...     }

    當(dāng)你使用await調(diào)用Promise的時(shí)候,你可以用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函數(shù)的簡潔語法,能夠給你帶來一些強(qiáng)大的能力。

    在下面這個簡單的例子中,你會看到我是如何利用async函數(shù)內(nèi)在的錯誤處理能力的,它讓我簡化了Express應(yīng)用中的錯誤處理流程。

     // 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函數(shù)中,這樣就極大的簡化了錯誤處理流程。

    我用了幾個小時(shí)的時(shí)間對數(shù)據(jù)庫進(jìn)行了遷移。要想使用這個方式,你唯一需要的,就是對Promise的深刻理解,以及學(xué)會如何設(shè)置babel。

    贊(0)
    分享到: 更多 (0)
    網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號