在nodejs中,await用於以非堵塞方式暫停執行,等待一個promise的非同步請求,一直等待非同步方法執行完畢;await可以用於async函數中,用於等待一個async函數的返回值;promise回傳的是拒絕不成功,拒絕值將會拋出,能夠被「try/catch」捕捉。
本文操作環境:Windows10系統、nodejs 12.19.0版、Dell G3電腦。
nodejs中await怎麼用
Node.js 7 night中引進了async/await用法,但在Node.js 8和Javascript V8才可能正式啟動async/await函式。
什麼是async/await?以前使用Promise是如何實現非同步操作的,以下案例是展示如何使用Promise和Fetch API抓取資料的:
function getTrace () { return fetch('https://www.jdon.com', { method: 'get' }) } getTrace() .then() .catch()
使用async/await,能以非堵塞方式暫停執行,一直等待結果返回,如果promise回傳的是拒絕不成功,拒絕值將會拋出,能夠被try/catch捕捉。上面案例可使用async/await寫成如下:
function async getTrace () { let pageContent try { pageContent = await fetch('https://www.jdon.com', { method: 'get' }) } catch (ex) { console.error(ex) } return pageContent } getTrace() .then()
再看看在Node.js中使用async/await案例,使用setimeout延遲一個函數執行,使用async/await封裝:
// app.js const timeout = function (delay) { return new Promise((resolve, reject) => { setTimeout(() => { resolve() }, delay) }) } async function timer () { console.log('timer started') await Promise.resolve(timeout(100)); console.log('timer finished') } timer()
建立好這個app.js文件,運行:
node app.js
如果不能運行,可能是nodejs是nightly版本,未正式支援async/await,命令列該為:
node --harmony-async-await app.js
推薦學習:《nodejs影片教學》
以上是nodejs中await怎麼用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潛在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

javascriptfatigueinrectismanagbaiblewithstrategiesLike just just in-timelearninganning and CuratedInformationsources.1)學習whatyouneedwhenyouneedit

tateractComponents通過theusestatehook,使用jestandReaCtTestingLibraryToSigulationsimintionsandIntractions and verifyStateChangesInTheUI.1)underthecomponentAndComponentAndComponentAndConconentAndCheckInitialState.2)模擬useruseruserusertactionslikeclicksorformsorformsormissions.3)

KeysinreactarecrucialforopTimizingPerformanceByingIneFefitedListupDates.1)useKeyStoIndentifyAndTrackListelements.2)避免使用ArrayIndicesasKeystopreventperformansissues.3)ChooSestableIdentifierslikeIdentifierSlikeItem.idtomaintainAinainCommaintOnconMaintOmentStateAteanDimpperperFermerfermperfermerformperfermerformfermerformfermerformfermerment.ChosestopReventPerformissues.3)

ReactKeySareUniqueIdentifiers usedwhenrenderingListstoimprovereConciliation效率。 1)heelPreactrackChangesInListItems,2)使用StableanDuniqueIdentifiersLikeItifiersLikeItemidSisRecumended,3)避免使用ArrayIndicesaskeyindicesaskeystopreventopReventOpReventSissUseSuseSuseWithReRefers和4)

獨特的keysarecrucialinreactforoptimizingRendering和MaintainingComponentStateTegrity.1)useanaturalAlaluniqueIdentifierFromyourDataiFabable.2)ifnonaturalalientedifierexistsistsists,generateauniqueKeyniqueKeyKeyLiquekeyperaliqeyAliqueLiqueAlighatiSaliqueLiberaryLlikikeuuId.3)deversearrayIndiceSaskeyseSecialIndiceSeasseAsialIndiceAseAsialIndiceAsiall


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Dreamweaver CS6
視覺化網頁開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。