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

Node.js Callback Functions

Node.js Callback Functions

Node.js is a JavaScript runtime based on the Chrome V8 engine, which allows JavaScript to run on the server side, outside the browser.

One of the core features of Node.js is its non-blocking I/O (input/output) model, which makes Node.js very suitable for handling high-concurrency network applications.

The direct manifestation of asynchronous programming in Node.js is callbacks.

In Node.js, a callback function is an asynchronous programming pattern used to handle I/O operations such as file reads and writes, database interactions, and network requests. These operations usually take a relatively long time; if a synchronous approach were used, it would block the entire program's execution until the operation completes.

Using callback functions, Node.js can continue executing other code while I/O operations are in progress, and execute the callback function once the I/O operation completes.

Node.js is single-threaded, but achieves asynchronous operations through event-driven and callback mechanisms.

Use Cases

For example, we can read a file while executing other commands; once the file read is complete, we return the file content as an argument to the callback function. In this way, there is no blocking or waiting for file I/O operations while executing code. This greatly improves the performance of Node.js, allowing it to handle a large number of concurrent requests.

A callback function generally appears as the last argument of a function:

function foo1(name, age, callback) { }
function foo2(value, callback1, callback2) { }

Example

Blocking code example

Create a file named input.txt with the following content:


Runoob Tutorial官网地址:www.runoob.com

Create a file named main.js with the following code:

Example

var

fs

=

require

(

"fs"

)

;

var

data

=

fs.

readFileSync

(

'input.txt'

)

;

console.

log

(

data.

toString

(

)

)

;

console.

log

(

"Program execution finished!"

)

;

The result of executing the above code is as follows:


$ node main.js
Runoob Tutorial官网地址:www.runoob.com

程序执行结束!

Non-blocking code example

Create a file named input.txt with the following content:


Runoob Tutorial官网地址:www.runoob.com

Create a file named main.js with the following code:

Example

var

fs

=

require

(

"fs"

)

;

fs.

readFile

(

'input.txt'

,

function

(

err

,

data

)

{

   

if

(

err

)

return

console.

error

(

err

)

;

    console.

log

(

data.

toString

(

)

)

;

}

)

;

console.

log

(

"Program execution finished!"

)

;

Parameter Explanations:

The result of executing the above code is as follows:


$ node main.js
程序执行结束!
Runoob Tutorial官网地址:www.runoob.com

From the above two examples, we understand the difference between blocking and non-blocking calls:

Therefore, blocking executes in sequence, while non-blocking does not need to follow a sequence, so if you need to handle the arguments of a callback function, you need to write them inside the callback function.


Callback Hell

When multiple asynchronous operations need to be executed in sequence, callback functions lead to code nesting, making the code difficult to read and maintain.

Example

fs.

readFile

(

'file1.txt'

,

'utf8'

,

(

err

,

data1

)

=>

{

   

if

(

err

)

{

        console.

error

(

'Error reading file1:'

,

err

)

;

       

return

;

   

}

    fs.

readFile

(

'file2.txt'

,

'utf8'

,

(

err

,

data2

)

=>

{

       

if

(

err

)

{

            console.

error

(

'Error reading file2:'

,

err

)

;

           

return

;

       

}

        fs.

readFile

(

'file3.txt'

,

'utf8'

,

(

err

,

data3

)

=>

{

           

if

(

err

)

{

                console.

error

(

'Error reading file3:'

,

err

)

;

               

return

;

           

}

            console.

log

(

'Data from all files:'

,

data1

,

data2

,

data3

)

;

       

}

)

;

   

}

)

;

}

)

;

To improve code readability and maintainability, you can use the following approaches:

1. Using async/await

async/await is syntactic sugar introduced in ES2017 that lets you handle asynchronous operations more conveniently and avoid callback hell.

Example

const

fs

=

require

(

'fs'

)

.

promises

;

async

function

readFiles

(

)

{

   

try

{

       

const

data1

=

await fs.

readFile

(

'file1.txt'

,

'utf8'

)

;

       

const

data2

=

await fs.

readFile

(

'file2.txt'

,

'utf8'

)

;

       

const

data3

=

await fs.

readFile

(

'file3.txt'

,

'utf8'

)

;

        console.

log

(

'Data from all files:'

,

data1

,

data2

,

data3

)

;

   

}

catch

(

err

)

{

        console.

error

(

'Error reading files:'

,

err

)

;

   

}

}

readFiles

(

)

;

2. Using Promises

Promises are another way to handle asynchronous operations, allowing you to chain the then method to avoid nested callbacks.

Example

const

fs

=

require

(

'fs'

)

.

promises

;

fs.

readFile

(

'file1.txt'

,

'utf8'

)

    .

then

(

data1

=>

{

        console.

log

(

'Data from file1:'

,

data1

)

;

       

return

fs.

readFile

(

'file2.txt'

,

'utf8'

)

;

   

}

)

    .

then

(

data2

=>

{

        console.

log

(

'Data from file2:'

,

data2

)

;

       

return

fs.

readFile

(

'file3.txt'

,

'utf8'

)

;

   

}

)

    .

then

(

data3

=>

{

        console.

log

(

'Data from file3:'

,

data3

)

;

   

}

)

    .

catch

(

err

=>

{

        console.

error

(

'Error reading files:'

,

err

)

;

   

}

)

;

Callback functions are a fundamental way to handle asynchronous operations in Node.js, but as application complexity increases, the problem of callback hell becomes more pronounced. By using async/await or Promises, you can significantly improve code readability and maintainability.