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

Node.js Asynchronous Programming

Node.js Asynchronous Programming

In traditional synchronous programming, code is executed sequentially; each line of code must wait for the previous line to finish before it can run. Asynchronous programming, on the other hand, allows code to continue executing other tasks while waiting for certain operations (such as I/O operations) to complete, without blocking the program.

Node.js adopts an asynchronous I/O model, which makes it particularly suitable for handling high-concurrency network applications. Understanding asynchronous programming is the key to mastering Node.js.


Why Node.js Needs Asynchronous Programming

Node.js is single-threaded, which means it can execute only one task at a time. If synchronous programming is used, when a time-consuming operation (such as reading a large file or a network request) is executed, the entire program will be blocked and unable to handle other requests.

Asynchronous programming solves this problem:


Three Main Ways of Asynchronous Programming in Node.js

1. Callback Functions (Callbacks)

A callback function is the most basic way of handling asynchronous operations in Node.js. It works by passing a function as an argument to another function, which is called after the operation completes.

Example

const

fs

=

require

(

'fs'

)

;

// Read a file asynchronously

fs.

readFile

(

'example.txt'

,

'utf8'

,

(

err

,

data

)

=>

{

 

if

(

err

)

{

    console.

error

(

'Error reading file:'

,

err

)

;

   

return

;

 

}

  console.

log

(

'File content:'

,

data

)

;

}

)

;

console.

log

(

'File read request sent, continuing to execute other code...'

)

;

Feature:

2、Promise

Promise is an asynchronous programming solution introduced in ES6; it represents the eventual completion or failure of an asynchronous operation and its resulting value.

Example

const

fs

=

require

(

'fs'

)

.

promises

;

// Read a file using Promise

fs.

readFile

(

'example.txt'

,

'utf8'

)

  .

then

(

data

=>

{

    console.

log

(

'File content:'

,

data

)

;

 

}

)

  .

catch

(

err

=>

{

    console.

error

(

'Error reading file:'

,

err

)

;

 

}

)

;

console.

log

(

'File read request sent, continuing to execute other code...'

)

;

Feature:

3、async/await

async/await is syntactic sugar introduced in ES8, based on Promises, making asynchronous code look like synchronous code.

Example

const

fs

=

require

(

'fs'

)

.

promises

;

async

function

readFile

(

)

{

 

try

{

   

const

data

=

await fs.

readFile

(

'example.txt'

,

'utf8'

)

;

    console.

log

(

'File content:'

,

data

)

;

 

}

catch

(

err

)

{

    console.

error

(

'Error reading file:'

,

err

)

;

 

}

}

readFile

(

)

;

console.

log

(

'File read request sent, continuing to execute other code...'

)

;

Feature:


Error handling best practices

Error Handling in Callback Functions

Example

fs.

readFile

(

'example.txt'

,

'utf8'

,

(

err

,

data

)

=>

{

 

if

(

err

)

{

    console.

error

(

'Error reading file:'

,

err

)

;

   

return

;

// Important: return after handling the error to avoid executing subsequent code

 

}

  console.

log

(

'File content:'

,

data

)

;

}

)

;

Error Handling in Promise

Example

fs.

readFile

(

'example.txt'

,

'utf8'

)

  .

then

(

data

=>

{

    console.

log

(

'File content:'

,

data

)

;

   

return

someOtherAsyncOperation

(

data

)

;

 

}

)

  .

then

(

result

=>

{

    console.

log

(

'Second step result:'

,

result

)

;

 

}

)

  .

catch

(

err

=>

{

    console.

error

(

'Error during processing:'

,

err

)

;

 

}

)

;

Error Handling in async/await

Example

async

function

processData

(

)

{

 

try

{

   

const

data

=

await fs.

readFile

(

'example.txt'

,

'utf8'

)

;

   

const

result

=

await someOtherAsyncOperation

(

data

)

;

    console.

log

(

'Final result:'

,

result

)

;

 

}

catch

(

err

)

{

    console.

error

(

'Error during processing:'

,

err

)

;

 

}

}

processData

(

)

;


Performance considerations

  1. Avoid blocking the event loop: Long-running synchronous code will block the entire application
  2. Use asynchronous operations reasonably: Not all operations need to be asynchronous; simple computational tasks may be more efficient when done synchronously
  3. Control the level of concurrency: Too many parallel asynchronous operations may lead to resource exhaustion
  4. Use streams to handle large files: For large files, use a Stream instead of reading all at once