日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網(wǎng)為廣大站長(zhǎng)提供免費(fèi)收錄網(wǎng)站服務(wù),提交前請(qǐng)做好本站友鏈:【 網(wǎng)站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(wù)(50元/站),

點(diǎn)擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會(huì)員:747

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


Node.js中async的用法是什么


nodejs中async的用法是什么

1、什么是 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ì)被拒絕。

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)


2、向 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)


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

3.1 在 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)

但正如 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)
}))


3.2 并行執(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)
}

在這個(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)
}

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


3.3 錯(cuò)誤處理

考慮下面這個(gè)例子:

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

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

(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 被拒絕且未得到處理,整個(gè) Node.js 進(jìn)程就會(huì)被中斷。因此必要的時(shí)候你應(yīng)該使用 try-catch:

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


分享到:
標(biāo)簽:Node.js async的用法
用戶無頭像

網(wǎng)友整理

注冊(cè)時(shí)間:

網(wǎng)站:5 個(gè)   小程序:0 個(gè)  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會(huì)員

趕快注冊(cè)賬號(hào),推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨(dú)大挑戰(zhàn)2018-06-03

數(shù)獨(dú)一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學(xué)四六

運(yùn)動(dòng)步數(shù)有氧達(dá)人2018-06-03

記錄運(yùn)動(dòng)步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績(jī)?cè)u(píng)定2018-06-03

通用課目體育訓(xùn)練成績(jī)?cè)u(píng)定