久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長(zhǎng)資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      理解JavaScript之Async/Await的新語(yǔ)法

      理解JavaScript之Async/Await的新語(yǔ)法

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

      首先我們先來(lái)了解兩個(gè)術(shù)語(yǔ):

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

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

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

      函數(shù)會(huì)返回一個(gè)Promise

      當(dāng)你用async關(guān)鍵詞創(chuàng)建一個(gè)函數(shù)的時(shí)候,這個(gè)函數(shù)永遠(yuǎn)都會(huì)返回一個(gè)Promise。當(dāng)你在async函數(shù)內(nèi)部進(jìn)行返回的時(shí)候,它會(huì)用一個(gè)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ù)還有一個(gè)特別之處,那就是它是唯一一個(gè)讓你使用await關(guān)鍵詞的地方。

      Await讓你可以暫停async函數(shù)的執(zhí)行,直到它受到了一個(gè)promise的結(jié)果。這讓你可以寫(xiě)出按照?qǐng)?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的情況下寫(xiě)異步代碼。這樣做的好處是讓你的代碼可讀性更高。而且await可以與任何promise兼容,而不僅僅是用async函數(shù)所創(chuàng)建的promise。

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

      因?yàn)閍sync函數(shù)也是一個(gè)Promise,當(dāng)你在代碼中放入一個(gè)async函數(shù)的時(shí)候,它會(huì)被吸收,然后作為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中添加一個(gè)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的錯(cuò)誤處理屬性,以及async函數(shù)的簡(jiǎn)潔語(yǔ)法,能夠給你帶來(lái)一些強(qiáng)大的能力。

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

       // 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)來(lái)處理錯(cuò)誤。然而,有了async/await,我們可以將錯(cuò)誤放在代碼中的任何位置,然后router會(huì)將這些錯(cuò)誤throw到Express提供的next函數(shù)中,這樣就極大的簡(jiǎn)化了錯(cuò)誤處理流程。

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

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