Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use callback in Node.js Asynchronous programming

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to use callback in Node.js asynchronous programming". In daily operation, I believe many people have doubts about how to use callback in Node.js asynchronous programming. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use callback in Node.js asynchronous programming". Next, please follow the editor to study!

Asynchronous programming case-function interview (callback) {setTimeout (() = > {callback ("success");}, 1000);} interview (function (res) {if (res = "success") {console.log ("= I smiled");}}); callback function format specification

Error-first callbak

Node-style callback

The first parameter is error, and the following parameter is the result

Why is the first parameter errorfunction 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);} 上面的代码中,try catch并不能捕获 throw new Error('fail') 抛出的错误!,而是抛出到了 JS 全局! 在 Node.js 中,全局错误时非常严重的事情,会造成程序的崩溃! 为什么没 try catch 无法捕获 setTimeout 里面的 throw 呢? 这就跟调用栈 和 事件循环有关系了! 每一个事件循环都是一个全新的调用栈! setTimeout 与 interview 是两个不同的事件循环! 但是可以通过在回调函数中的参数抛出错误的方式来解决这个问题 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("============我笑了");}); 上面的代码中,可以根据参数的类型来判断是否出错! 但是 Node.js 中有很对回调函数, 我们不可能在每一个函数中都去判断参数类型是是否出错! Node.js 规定第一个参数就是 erro,第二个参数就是结果!如果第一个参数不为空,则说明异步调用出错了! 异步流程控制的问题回调地狱 多个异步任务串行的情况, 下面我们模拟一下 N 轮面试, 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 interview = I cried") } interview (function (error) {if (error) {return console.log ("= second round interview = I cried");} interview (function (error) {if (error) {return console.log ("= third round interview = I cried");} console.log ("all three rounds of interviews were successful! Ah ha ha! ") ;}))

You can see that the above asynchronous process has three layers of nesting, which is just a relatively simple case of the code! Then in practical application, each nested function may be very complex, which makes it difficult to develop and maintain, which makes people angry. This is the so-called * * callback dungeon * *.

A

The concurrency of multiple asynchronous tasks

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 have successful interviews! I laughed ");}});} interviewCompay ()

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

At this point, the study on "how to use callback in Node.js asynchronous programming" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report