Home > Web Front-end > JS Tutorial > An in-depth analysis of callback in Node.js asynchronous programming

An in-depth analysis of callback in Node.js asynchronous programming

青灯夜游
Release: 2021-07-06 11:31:05
forward
2710 people have browsed it

The running results of non-blocking I/O require a callback function to receive. The following article will give you a detailed introduction to Node.jscallback (callback) in asynchronous programming.

An in-depth analysis of callback in Node.js asynchronous programming

[Recommended study: "nodejs Tutorial"]

The running result of non-blocking I/O requires a callback function to receive Yes, this way of using callback functions is asynchronous programming!

Asynchronous Programming Case 1

function interview(callback) {
  setTimeout(() => {
    callback("success");
  }, 1000);
}

interview(function (res) {
  if (res === "success") {
    console.log("============我笑了");
  }
});
Copy after login

Callback function format specification

    ##error-first callbak
  • Node-style callback
  • The first parameter is error, and the following parameters are the result

Why the first parameter is error
function interview(callback) {
  setTimeout(() => {
    if (Math.random() < 0.3) {
      callback("success");
    }
    throw new Error("fail");
  }, 1000);
}

try {
  interview(function (res) {
    if (res === "success") {
      console.log("============我笑了");
    }
  });
} catch (error) {
  console.log("fail", error);
}
Copy after login

An in-depth analysis of callback in Node.js asynchronous programming

In the above code,

try catch cannot capture the error thrown by throw new Error('fail')! , but thrown to the JS global! In Node.js, global errors are very serious things and can cause the program to crash!

Why is there no

try catch that cannot capture the throw in setTimeout? This has something to do with call stack and event loop!

Each event loop is a brand new call stack! setTimeout and interview are two different event loops!

But you can solve this problem by throwing an error in the parameters in the callback function

function interview(callback) {
  setTimeout(() => {
    if (Math.random() < 0.3) {
      callback(null, "success");
    } else {
      callback(new Error("fail"));
    }
  }, 1000);
}

interview(function (error) {
  if (error) {
    return console.log("============我哭了");
  }
  console.log("============我笑了");
});
Copy after login

In the above code, you can solve the problem according to the type of the parameters. to determine whether there is an error! But there are many callback functions in Node.js, and it is impossible for us to judge whether the parameter type is wrong in every function!

Node.js stipulates that the first parameter is erro, and the second parameter is the result! If the first parameter is not empty, there is an error in the asynchronous call!

Problems with asynchronous process control

Callback hell

The situation of multiple asynchronous tasks serially, as follows Let's simulate N rounds of interviews.

function interview(callback) {
  setTimeout(() => {
    if (Math.random() < 0.6) {
      callback(null, "success");
    } else {
      callback(new Error("fail"));
    }
  }, 1000);
}

interview(function (error) {
  if (error) {
    return console.log("======第一轮面试======我哭了");
  }

  interview(function (error) {
    if (error) {
      return console.log("====第二轮面试========我哭了");
    }

    interview(function (error) {
      if (error) {
        return console.log("====第三轮面试========我哭了");
      }

      console.log("三轮面试都成功了!啊哈哈哈!");
    });
  });
});
Copy after login

You can see that the above asynchronous process has three levels of nesting. This is just a situation where the code is relatively simple! So in actual applications, each nested function may be very complex, which makes it difficult to develop and maintain, and makes people angry when looking at it. This is the so-called ** callback hell **

a

Concurrent situation of multiple asynchronous tasks

function interviewCompay() {
  let count = 0;
  interview(function (error) {
    if (error) {
      return console.log("====第一家公司面试========我哭了");
    }
    count++;
  });
  interview(function (error) {
    if (error) {
      return console.log("====第二家公司面试========我哭了");
    }
    count++;
    if (count === 2) {
      return console.log("两家公司面试都成功了!我笑了");
    }
  });
}
interviewCompay();
Copy after login
The same variable needs to be added to each asynchronous task to capture the results of multiple asynchronous tasks

Solving the control problem of asynchronous processes

    promise
  • async await
For more programming-related knowledge, please visit:

Programming video! !

The above is the detailed content of An in-depth analysis of callback in Node.js asynchronous programming. For more information, please follow other related articles on the PHP Chinese website!

source:juejin.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template