search
HomeWeb Front-endJS TutorialAn 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.jscallbackAsynchronous 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("============我笑了");
  }
});

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);
}

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("============我笑了");
});

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("三轮面试都成功了!啊哈哈哈!");
    });
  });
});

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();

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
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.