This is the twenty-sixth day of my participation in wen Challenge

The callback function is required to receive the operating results of fiber () non-blocking I/O. This way of getting through the callback function is asynchronous programming!

Asynchronous programming case one

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

interview(function (res) {
  if (res === "success") {
    console.log("============ I laughed"); }});Copy the code

Callback function format specification

  • error-first callbak
  • Node-style callback
  • The first argument is error, and the following arguments are the results

Why is the first argument 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("============ I laughed"); }}); }catch (error) {
  console.log("fail", error);
}
Copy the code

In the above code, a try catch does not catch errors thrown by throw new Error(‘fail’)! Instead, it throws the JS global! In Node.js, a global error is a very serious matter and can cause an application to crash!

Why can’t we catch a throw inside a setTimeout without a try catch? This has to do with call stacks and event loops!

Each event loop is a new call stack!setTimeoutInterview is two different cycles of events!

But you can solve this problem by throwing an error as an argument 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("============ I cried");
  }
  console.log("============ I laughed");
});
Copy the code

In the above code, you can determine whether an error occurs according to the type of the parameter! But there are so many callback functions in Node.js that it’s impossible to tell if the argument type is wrong in every one of them!

Node.js specifies that the first argument is erro and the second argument is the result! If the first parameter is not null, then the asynchronous call went wrong!

Problems with asynchronous process control

The callback hell

In the case of serial asynchronous tasks, 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("====== first round of interview ====== I cried");
  }

  interview(function (error) {
    if (error) {
      return console.log("==== second round of interview ======== I cried");
    }

    interview(function (error) {
      if (error) {
        return console.log("==== third round interview ======== I cried");
      }

      console.log("Three rounds of interviews! Aha!");
    });
  });
});
Copy the code

You can see that the above asynchronous process has three layers of nesting, and this is just the code is relatively simple! In practice, then, each nested function can be very complex, which makes it difficult to develop and maintain, which makes it infuriating to watch 💢, which is called callback hell

a

Multiple asynchronous tasks running concurrently

function interviewCompay() {
  let count = 0;
  interview(function (error) {
    if (error) {
      return console.log("==== first company interview ======== I cried");
    }
    count++;
  });
  interview(function (error) {
    if (error) {
      return console.log("==== second company interview ======== I cried");
    }
    count++;
    if (count === 2) {
      return console.log("Both companies had successful interviews! I smiled. ""); }}); } interviewCompay();Copy the code

The same variable needs to be added to each asynchronous task to capture the results of multiple asynchronous tasks

Resolve control issues for asynchronous processes

  • promise
  • async await

The last

This article is shallow, you are welcome to see the officer comments left your opinion!

Feel the harvest of the students welcome to like, pay attention to a wave!

The articles

  • The most complete ECMAScript walkthrough
  • What is the principle of qr code scanning login
  • 15 front-end hd knowledge map, strongly recommended collection
  • Front end developers should know Centos/Docker/Nginx/Node/Jenkins (🍡 long)
  • Let me tell you about some awesome NPM packages