Home >Web Front-end >Front-end Q&A >what is nodejs callback hell
In nodejs, the results of "I/O" operations basically need to be processed in the callback function. When processing multiple events, the callback function will be nested layer by layer. This is callback hell; That is, an asynchronous request is nested within an asynchronous request, and one asynchronous request depends on the execution result of the other, using callbacks to nest each other.
The operating environment of this article: Windows 10 system, nodejs version 12.19.0, Dell G3 computer.
The results of I/O operations in nodejs basically need to be processed in the callback function. When multiple events are processed, the callback function will be embedded layer by layer. Well, this is callback hell.
An asynchronous request is nested within an asynchronous request. One asynchronous request depends on the execution result of the other, using callbacks to nest each other.
The biggest highlight of Nodejs is that it is event-driven and non-blocking I/O model, which makes Nodejs have strong concurrent processing capabilities and is very suitable for writing network applications. Most I/O operations in Nodejs are almost asynchronous, that is, the results of our I/O operations basically need to be processed in callback functions, such as the following function that reads file content:
fs.readFile('/etc/passwd', function (err, data) { if (err) throw err; console.log(data); });
Then, what should we do if we read two files and merge the contents of the two files together for processing? Most people who have been exposed to js for a short time may do this:
fs.readFile('/etc/passwd', function (err, data) { if (err) throw err; fs.readFile('/etc/passwd2', function (err, data2) { if (err) throw err; // 在这里处理data和data2的数据 }); });
What if we process it? There are multiple similar scenarios, and the callback functions are nested layer by layer. This is what everyone often calls the callback pyramid or callback hell.
Recommended learning: "nodejs video tutorial"
The above is the detailed content of what is nodejs callback hell. For more information, please follow other related articles on the PHP Chinese website!