Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js async/await

Node.js async/await

In Node.js,async/await is syntactic sugar for handling asynchronous operations.

async/await It is based on Promises, but makes asynchronous code look more like synchronous code, greatly improving the readability and maintainability of the code.

async The keyword is used to declare that a function is asynchronous, while await the keyword is used to wait for the resolution or rejection of a Promise.

Use async/await can avoid callback hell and make error handling more intuitive.

JavaScript is single-threaded; when it encounters an asynchronous task (such as setTimeout or a network request), it hands it over to the browser APIs for processing, and when complete, places the callback into the message queue.

The event loop continuously checks whether the call stack is empty, and if so, takes a callback from the queue and pushes it onto the call stack for execution. This way, the main thread is not blocked, and asynchronous results are processed in order.


Basic Syntax

async Functions

Any function can be made asynchronous by adding the async keyword:

async

function

myFunction

(

)

{

 

return

"Hello World"

;

}

async A function always returns a Promise. If the return value is not a Promise, it is automatically wrapped into a Promise.

await expression

await can only be used inside async functions; it pauses the execution of the function, waits for the Promise to resolve, then continues execution and returns the result:

async

function

fetchData

(

)

{

 

const

response

=

await fetch

(

'https://api.example.com/data'

)

;

 

const

data

=

await response.

json

(

)

;

 

return

data

;

}


Error handling

The try/catch approach

Handling async/await The most common way to handle errors is to use try/catch:

Example

async

function

getUser

(

)

{

 

try

{

   

const

response

=

await fetch

(

'https://api.example.com/user'

)

;

   

const

user

=

await response.

json

(

)

;

   

return

user

;

 

}

catch

(

error

)

{

    console.

error

(

'Error fetching user:'

,

error

)

;

   

throw

error

;

// You can choose to rethrow the error

 

}

}

Handle the Promise directly

You can also handle the returned Promise directly:

Example

getUser

(

)

  .

then

(

user

=>

console.

log

(

user

)

)

  .

catch

(

error

=>

console.

error

(

error

)

)

;


Practical Application Examples

Execute multiple asynchronous operations in parallel

Use Promise.all combined with async/await You can execute multiple asynchronous operations in parallel:

Example

async

function

fetchMultipleUrls

(

urls

)

{

 

try

{

   

const

requests

=

urls.

map

(

url

=>

fetch

(

url

)

)

;

   

const

responses

=

await Promise.

all

(

requests

)

;

   

const

data

=

await Promise.

all

(

responses.

map

(

r

=>

r.

json

(

)

)

)

;

   

return

data

;

 

}

catch

(

error

)

{

    console.

error

(

'Error fetching data:'

,

error

)

;

   

throw

error

;

 

}

}

Database Operation Example

Example

async

function

getUserAndPosts

(

userId

)

{

 

try

{

   

const

user

=

await User.

findById

(

userId

)

;

   

const

posts

=

await Post.

find

(

{

userId

}

)

;

   

return

{

user

,

posts

}

;

 

}

catch

(

error

)

{

    console.

error

(

'Database error:'

,

error

)

;

   

throw

error

;

 

}

}


Best Practices

  1. Always handle errors: Do not ignore await errors that may be thrown; use try/catch or .catch() Handling
  2. Avoid unnecessary await: If you don't need to wait for the result, you can return the Promise directly
  3. Use parallelism reasonably: Multiple independent asynchronous operations should be executed in parallel (using Promise.all)
  4. Keep the code clear: Avoid excessively deep async/await nesting; extract functions when necessary
  5. Be Aware of Performance Impact: Each await pauses function execution, so pay special attention in loops

Common questions

The Relationship Between async/await and Promise

async/await is syntactic sugar built on top of Promises. Any async function returns a Promise, and any await can be followed by a Promise.

Why does my async function return undefined?

This may be because you forgot to use await before return, or the function exited before the Promise resolved.

Can I use await at the top level?

In ES modules (files ending with .mjs or with package.json Medium "type": "module"), you can use awaitdirectly at the top level. In CommonJS modules, you need to wrap it in an async function.

Example

// In ES modules

const

data

=

await fetchData

(

)

;

console.

log

(

data

)

;