久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放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)站

      聊聊Node.js中怎么用async函數(shù)

      聊聊Node.js中怎么用async函數(shù)

      借助于新版 V8 引擎,Node.js 從 7.6 開始支持 async 函數(shù)特性。今年 10 月 31 日,Node.js 8 也開始成為新的長(zhǎng)期支持版本,因此你完全可以放心大膽地在你的代碼中使用 async 函數(shù)了。在這邊文章里,我會(huì)簡(jiǎn)要地介紹一下什么是 async 函數(shù),以及它會(huì)如何改變我們編寫 Node.js 應(yīng)用的方式。

      什么是 async 函數(shù)

      利用 async 函數(shù),你可以把基于 Promise 的異步代碼寫得就像同步代碼一樣。一旦你使用 async 關(guān)鍵字來定義了一個(gè)函數(shù),那你就可以在這個(gè)函數(shù)內(nèi)使用 await 關(guān)鍵字。當(dāng)一個(gè) async 函數(shù)被調(diào)用時(shí),它會(huì)返回一個(gè) Promise。當(dāng)這個(gè) async 函數(shù)返回一個(gè)值時(shí),那個(gè) Promise 就會(huì)被實(shí)現(xiàn);而如果函數(shù)中拋出一個(gè)錯(cuò)誤,那么 Promise 就會(huì)被拒絕?!鞠嚓P(guān)教程推薦:nodejs視頻教程、編程教學(xué)】

      await 關(guān)鍵字可以被用來等待一個(gè) Promise 被解決并返回其實(shí)現(xiàn)的值。如果傳給 await 的值不是一個(gè) Promise,那它會(huì)把這個(gè)值轉(zhuǎn)化為一個(gè)已解決的 Promise。

      const rp = require('request-promise') async function main () {  const result = await rp('https://google.com')  const twenty = await 20  // 睡個(gè)1秒鐘  await new Promise (resolve => {   setTimeout(resolve, 1000)  })  return result } main()  .then(console.log)  .catch(console.error)
      登錄后復(fù)制

      向 async 函數(shù)遷移

      如果你的 Node.js 應(yīng)用已經(jīng)在使用Promise,那你只需要把原先的鏈?zhǔn)秸{(diào)用改寫為對(duì)你的這些 Promise 進(jìn)行 await。

      如果你的應(yīng)用還在使用回調(diào)函數(shù),那你應(yīng)該以漸進(jìn)的方式轉(zhuǎn)向使用 async 函數(shù)。你可以在開發(fā)一些新功能的時(shí)候使用這項(xiàng)新技術(shù)。當(dāng)你必須調(diào)用一些舊有的代碼時(shí),你可以簡(jiǎn)單地把它們包裹成為 Promise 再用新的方式調(diào)用。

      要做到這一點(diǎn),你可以使用內(nèi)建的 util.promisify方法:

      const util = require('util') const {readFile} = require('fs') const readFileAsync = util.promisify(readFile) async function main () {  const result = await readFileAsync('.gitignore')  return result } main()  .then(console.log)  .catch(console.error)
      登錄后復(fù)制

      Async 函數(shù)的最佳實(shí)踐

      在 express 中使用 async 函數(shù)

      express 本來就支持 Promise,所以在 express 中使用 async 函數(shù)是比較簡(jiǎn)單的:

      const express = require('express') const app = express() app.get('/', async (request, response) => {  // 在這里等待 Promise  // 如果你只是在等待一個(gè)單獨(dú)的 Promise,你其實(shí)可以直接將將它作為返回值返回,不需要使用 await 去等待。  const result = await getContent()  response.send(result) }) app.listen(process.env.PORT)
      登錄后復(fù)制

      但正如 Keith Smith 所指出的,上面這個(gè)例子有一個(gè)嚴(yán)重的問題——如果 Promise 最終被拒絕,由于這里沒有進(jìn)行錯(cuò)誤處理,那這個(gè) express 路由處理器就會(huì)被掛起。

      為了修正這個(gè)問題,你應(yīng)該把你的異步處理器包裹在一個(gè)對(duì)錯(cuò)誤進(jìn)行處理的函數(shù)中:

      const awaitHandlerFactory = (middleware) => {  return async (req, res, next) => {   try {    await middleware(req, res, next)   } catch (err) {    next(err)   }  } } // 然后這樣使用: app.get('/', awaitHandlerFactory(async (request, response) => {  const result = await getContent()  response.send(result) }))
      登錄后復(fù)制

      并行執(zhí)行

      比如說你正在編寫這樣一個(gè)程序,一個(gè)操作需要兩個(gè)輸入,其中一個(gè)來自于數(shù)據(jù)庫,另一個(gè)則來自于一個(gè)外部服務(wù):

      async function main () {  const user = await Users.fetch(userId)  const product = await Products.fetch(productId)  await makePurchase(user, product) }
      登錄后復(fù)制

      在這個(gè)例子中,會(huì)發(fā)生什么呢?

      你的代碼會(huì)首先去獲取 user,

      然后獲取 product,

      最后再進(jìn)行支付。

      如你所見,由于前兩步之間并沒有相互依賴關(guān)系,其實(shí)你完全可以將它們并行執(zhí)行。這里,你應(yīng)該使用 Promise.all 方法:

      async function main () {  const [user, product] = await Promise.all([   Users.fetch(userId),   Products.fetch(productId)  ])  await makePurchase(user, product) }
      登錄后復(fù)制

      而有時(shí)候,你只需要其中最快被解決的 Promise 的返回值——這時(shí),你可以使用 Promise.race 方法。

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