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

JavaScript async/await

JavaScript async/await

Before explaining async/await, we need to first understand the concept of asynchronous programming in JavaScript; you can refer to:JavaScript Asynchronous Programming。

JavaScript is a single-threaded language, which means it can only execute one task at a time. To prevent long-running tasks from blocking the main thread, JavaScript uses an asynchronous programming model.

Asynchronous vs Synchronous

Example

// Synchronous example

console.

log

(

'1'

)

;

console.

log

(

'2'

)

;

// Output: 1, 2

// Asynchronous example

console.

log

(

'1'

)

;

setTimeout

(

(

)

=>

console.

log

(

'2'

)

,

0

)

;

console.

log

(

'3'

)

;

// Output: 1, 3, 2


The Problem with Callback Functions

Before async/await appeared, JavaScript mainly used callback functions to handle asynchronous operations, but this leads to "callback hell" (Callback Hell).

Example

getData

(

function

(

a

)

{

  getMoreData

(

a

,

function

(

b

)

{

    getMoreData

(

b

,

function

(

c

)

{

      getMoreData

(

c

,

function

(

d

)

{

        console.

log

(

d

)

;

     

}

)

;

   

}

)

;

 

}

)

;

}

)

;

This nested structure makes the code difficult to read and maintain.


The Introduction of Promise

ES6 introduced the Promise object to solve the callback hell problem.

Example

function

getData

(

)

{

 

return

new

Promise

(

(

resolve

,

reject

)

=>

{

   

// Asynchronous operation

    setTimeout

(

(

)

=>

resolve

(

'data'

)

,

1000

)

;

 

}

)

;

}

getData

(

)

  .

then

(

data

=>

{

    console.

log

(

data

)

;

   

return

getMoreData

(

data

)

;

 

}

)

  .

then

(

moreData

=>

{

    console.

log

(

moreData

)

;

 

}

)

  .

catch

(

error

=>

{

    console.

error

(

error

)

;

 

}

)

;

Although Promise improves the callback problem, then() chained calls are still not intuitive enough.


async/await Syntax

ES2017 introduced async/await, which builds on Promise and makes asynchronous code look like synchronous code.

async Functions

Add the async keyword before a function declaration to indicate that the function is asynchronous:

async

function

fetchData

(

)

{

 

// Function body

}

An async function always returns a Promise:

await expression

await can only be used inside an async function:

async

function

fetchData

(

)

{

 

const

result

=

await somePromise

;

  console.

log

(

result

)

;

}

await pauses the execution of the async function, waiting for the Promise to settle:


Practical Application Examples

Basic Usage

Example

function

delay

(

ms

)

{

 

return

new

Promise

(

resolve

=>

setTimeout

(

resolve

,

ms

)

)

;

}

async

function

showMessage

(

)

{

  console.

log

(

'start'

)

;

  await delay

(

1000

)

;

  console.

log

(

'after 1 second'

)

;

  await delay

(

1000

)

;

  console.

log

(

'after another 1 second'

)

;

}

showMessage

(

)

;

Error handling

Example

async

function

fetchUserData

(

)

{

 

try

{

   

const

response

=

await fetch

(

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

)

;

   

if

(

!

response.

ok

)

{

     

throw

new

Error

(

'network response is abnormal'

)

;

   

}

   

const

data

=

await response.

json

(

)

;

    console.

log

(

data

)

;

 

}

catch

(

error

)

{

    console.

error

(

'failed to get data:'

,

error

)

;

 

}

}

Parallel execution

If you need to execute multiple asynchronous operations in parallel, you can use Promise.all:

Example

async

function

fetchMultipleData

(

)

{

 

const

[

userData

,

productData

]

=

await Promise.

all

(

[

    fetch

(

'/api/user'

)

,

    fetch

(

'/api/products'

)

 

]

)

;

 

 

const

user

=

await userData.

json

(

)

;

 

const

products

=

await productData.

json

(

)

;

 

 

return

{

user

,

products

}

;

}


Common problems and best practices

1. Do not forget await

Example

// Wrong example - forgetting await

async

function

example

(

)

{

 

const

data

=

fetch

(

'/api'

)

;

// Missing await

  console.

log

(

data

)

;

// Outputs a Promise object

}

// Correct example

async

function

example

(

)

{

 

const

data

=

await fetch

(

'/api'

)

;

  console.

log

(

data

)

;

// Outputs the actual data

}

2. Avoid unnecessary async

Example

// Unnecessary - there is no await inside the function

async

function

unnecessaryAsync

(

)

{

 

return

42

;

}

// A simpler way to write it

function

simpleFunction

(

)

{

 

return

42

;

}

3. Top-level await

At the top level of a module, await can be used directly (an ES2022 feature):

Example

// In a module

const

data

=

await fetch

(

'/api'

)

;

console.

log

(

data

)

;

4. Performance Considerations


async/await vs Traditional Promise

Feature async/await Promise then/catch
Readability High, similar to synchronous code Medium, chained calls
Error handling Uses try/catch Uses .catch()
Debugging Easier, with a clear call stack Harder, the call stack may be unclear
Code structure Flatter Nested or chained

Summary

async/await is a major improvement in JavaScript asynchronous programming. It:

  1. makes asynchronous code easier to read and maintain
  2. is based on Promise and compatible with existing Promise code
  3. provides a more intuitive way to handle errors
  4. improves the debugging experience

Although async/await does not completely replace Promise, in most cases it provides a more elegant solution. Understanding how async/await works and its best practices will greatly improve your JavaScript asynchronous programming skills.