Home  >  Article  >  Web Front-end  >  what is nodejs callback hell

what is nodejs callback hell

WBOY
WBOYOriginal
2022-03-04 16:07:051892browse

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.

what is nodejs callback hell

The operating environment of this article: Windows 10 system, nodejs version 12.19.0, Dell G3 computer.

What is nodejs callback hell

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn