Table of Contents
Asynchronous Programming Case 1
Callback function format specification
Problems with asynchronous process control
Callback hell
a
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

Jul 06, 2021 am 11:30 AM
node.js callback Asynchronous programming

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement asynchronous programming with C++ functions? How to implement asynchronous programming with C++ functions? Apr 27, 2024 pm 09:09 PM

Summary: Asynchronous programming in C++ allows multitasking without waiting for time-consuming operations. Use function pointers to create pointers to functions. The callback function is called when the asynchronous operation completes. Libraries such as boost::asio provide asynchronous programming support. The practical case demonstrates how to use function pointers and boost::asio to implement asynchronous network requests.

Asynchronous Programming of JavaScript Functions: Essential Tips for Handling Complex Tasks Asynchronous Programming of JavaScript Functions: Essential Tips for Handling Complex Tasks Nov 18, 2023 am 10:06 AM

JavaScript Function Asynchronous Programming: Essential Skills for Handling Complex Tasks Introduction: In modern front-end development, handling complex tasks has become an indispensable part. JavaScript function asynchronous programming skills are the key to solving these complex tasks. This article will introduce the basic concepts and common practical methods of JavaScript function asynchronous programming, and provide specific code examples to help readers better understand and use these techniques. 1. Basic concepts of asynchronous programming In traditional synchronous programming, the code is

In-depth understanding of the new features of PHP8: How to use asynchronous programming and code efficiently? In-depth understanding of the new features of PHP8: How to use asynchronous programming and code efficiently? Sep 11, 2023 pm 01:52 PM

In-depth understanding of the new features of PHP8: How to use asynchronous programming and code efficiently? PHP8 is the latest major version of the PHP programming language, bringing many exciting new features and improvements. One of the most prominent features is support for asynchronous programming. Asynchronous programming allows us to improve performance and responsiveness when dealing with concurrent tasks. This article will take an in-depth look at PHP8’s asynchronous programming features and introduce how to use them efficiently. First, let’s understand what asynchronous programming is. In the traditional synchronous programming model, code follows a linear sequence

Common problems and solutions in asynchronous programming in Java framework Common problems and solutions in asynchronous programming in Java framework Jun 04, 2024 pm 05:09 PM

3 common problems and solutions in asynchronous programming in Java frameworks: Callback Hell: Use Promise or CompletableFuture to manage callbacks in a more intuitive style. Resource contention: Use synchronization primitives (such as locks) to protect shared resources, and consider using thread-safe collections (such as ConcurrentHashMap). Unhandled exceptions: Explicitly handle exceptions in tasks and use an exception handling framework (such as CompletableFuture.exceptionally()) to handle exceptions.

How does the golang framework handle concurrency and asynchronous programming? How does the golang framework handle concurrency and asynchronous programming? Jun 02, 2024 pm 07:49 PM

The Go framework uses Go's concurrency and asynchronous features to provide a mechanism for efficiently handling concurrent and asynchronous tasks: 1. Concurrency is achieved through Goroutine, allowing multiple tasks to be executed at the same time; 2. Asynchronous programming is implemented through channels, which can be executed without blocking the main thread. Task; 3. Suitable for practical scenarios, such as concurrent processing of HTTP requests, asynchronous acquisition of database data, etc.

Robot ETF (562500) may usher in a good layout opportunity because it has pulled back for 3 consecutive days! Robot ETF (562500) may usher in a good layout opportunity because it has pulled back for 3 consecutive days! Dec 01, 2023 pm 04:01 PM

In early trading on December 1, 2023, the three major stock indexes opened lower. The Robot ETF (562500) began to trade sideways after falling early in the session. As of 10:20, the Robot ETF (562500) fell 0.92%, with more than 60 of the 82 holdings falling. Daheng Technology and Shitou Technology fell by more than 5%, and Sukron Technology, Keda Intelligence, Xianhui Technology, and Hongxun Technology fell by more than 3%. As of early trading today, the Robot ETF (562500) has been correcting for three consecutive days. Looking back on the situation in the past month, the Robot ETF (562500) has only had one correction for three consecutive days, and then ushered in eight consecutive positive trends. This pullback may be a good layout opportunity following the announcement by relevant departments in early November.

Python asynchronous programming: A way to achieve efficient concurrency in asynchronous code Python asynchronous programming: A way to achieve efficient concurrency in asynchronous code Feb 26, 2024 am 10:00 AM

1. Why use asynchronous programming? Traditional programming uses blocking I/O, which means that the program waits for an operation to complete before continuing. This may work well for a single task, but may cause the program to slow down when processing a large number of tasks. Asynchronous programming breaks the limitations of traditional blocking I/O and uses non-blocking I/O, which means that the program can distribute tasks to different threads or event loops for execution without waiting for the task to complete. This allows the program to handle multiple tasks simultaneously, improving the program's performance and efficiency. 2. The basis of Python asynchronous programming The basis of Python asynchronous programming is coroutines and event loops. Coroutines are functions that allow a function to switch between suspending and resuming. The event loop is responsible for scheduling

What are the advantages and disadvantages of asynchronous programming in PHP? What are the advantages and disadvantages of asynchronous programming in PHP? May 06, 2024 pm 10:00 PM

The advantages of asynchronous programming in PHP include higher throughput, lower latency, better resource utilization, and scalability. Disadvantages include complexity, difficulty in debugging, and limited library support. In the actual case, ReactPHP is used to handle WebSocket connections, demonstrating the practical application of asynchronous programming.

See all articles