溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

nodejs中async怎么用

發(fā)布時間:2022-01-10 11:35:06 來源:億速云 閱讀:171 作者:iii 欄目:web開發(fā)

今天小編給大家分享一下nodejs中async怎么用的相關(guān)知識點,內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

在nodejs中,async關(guān)鍵字可以用于定義一個函數(shù),當(dāng)async函數(shù)被調(diào)用時,會返回一個Promise,當(dāng)async函數(shù)返回一個值時,這個Promise就會被實現(xiàn),當(dāng)函數(shù)拋出一個錯誤時,Promise就會被拒絕。

本教程操作環(huán)境:windows10系統(tǒng)、nodejs 12.19.0版,DELL G3電腦。

nodejs中async的用法是什么

1 什么是 async 函數(shù)

利用 async 函數(shù),你可以把基于 Promise 的異步代碼寫得就像同步代碼一樣。一旦你使用 async 關(guān)鍵字來定義了一個函數(shù),那你就可以在這個函數(shù)內(nèi)使用 await 關(guān)鍵字。當(dāng)一個 async 函數(shù)被調(diào)用時,它會返回一個 Promise。當(dāng)這個 async 函數(shù)返回一個值時,那個 Promise 就會被實現(xiàn);而如果函數(shù)中拋出一個錯誤,那么 Promise 就會被拒絕。

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

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

2 向 async 函數(shù)遷移

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

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

要做到這一點,你可以使用內(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)

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

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

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

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

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

為了修正這個問題,你應(yīng)該把你的異步處理器包裹在一個對錯誤進行處理的函數(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)
}))

3.2 并行執(zhí)行

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

async function main () {
 const user = await Users.fetch(userId)
 const product = await Products.fetch(productId)
 await makePurchase(user, product)
}

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

你的代碼會首先去獲取 user,

然后獲取 product,

最后再進行支付。

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

async function main () {
 const [user, product] = await Promise.all([
  Users.fetch(userId),
  Products.fetch(productId)
 ])
 await makePurchase(user, product)
}

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

3.3 錯誤處理

考慮下面這個例子:

async function main () {
 await new Promise((resolve, reject) => {
  reject(new Error('error'))
 })
}
main()
 .then(console.log)

當(dāng)執(zhí)行這段代碼的時候,你會看到類似這樣的信息:

(node:69738) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: error

(node:69738) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

在較新的 Node.js 版本中,如果 Promise 被拒絕且未得到處理,整個 Node.js 進程就會被中斷。因此必要的時候你應(yīng)該使用 try-catch:

const util = require('util')
async function main () {
 try {
  await new Promise((resolve, reject) => {
   reject(new Error('

以上就是“nodejs中async怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI