如何避免在 Node.js 中长时间嵌套异步函数 [英] How to avoid long nesting of asynchronous functions in Node.js

查看:18
本文介绍了如何避免在 Node.js 中长时间嵌套异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个页面来显示来自数据库的一些数据,所以我创建了一些从我的数据库获取数据的函数.我只是 Node.js 的新手,据我所知,如果我想在一个页面(HTTP 响应)中使用所有这些,我必须将它们全部嵌套:

I want to make a page that displays some data from a DB, so I have created some functions that get that data from my DB. I'm just a newbie in Node.js, so as far as I understand, if I want to use all of them in a single page (HTTP response) I'd have to nest them all:

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var html = "<h1>Demo page</h1>";
  getSomeDate(client, function(someData) {
    html += "<p>"+ someData +"</p>";
    getSomeOtherDate(client, function(someOtherData) {
      html += "<p>"+ someOtherData +"</p>";
      getMoreData(client, function(moreData) {
        html += "<p>"+ moreData +"</p>";
        res.write(html);
        res.end();
      });
    });
  });

如果有很多这样的函数,那么嵌套就会成为问题.

If there are many functions like that, then the nesting becomes a problem.

有没有办法避免这种情况?我想这与你如何组合多个异步函数有关,这似乎是一些基本的东西.

Is there a way to avoid this? I guess it has to do with how you combine multiple asynchronous functions, which seems to be something fundamental.

推荐答案

有趣的观察.请注意,在 JavaScript 中,您通常可以用命名函数变量替换内联匿名回调函数.

Interesting observation. Note that in JavaScript you can normally replace inline anonymous callback functions with named function variables.

以下内容:

http.createServer(function (req, res) {
   // inline callback function ...

   getSomeData(client, function (someData) {
      // another inline callback function ...

      getMoreData(client, function(moreData) {
         // one more inline callback function ...
      });
   });

   // etc ...
});

可以改写成这样:

var moreDataParser = function (moreData) {
   // date parsing logic
};

var someDataParser = function (someData) {
   // some data parsing logic

   getMoreData(client, moreDataParser);
};

var createServerCallback = function (req, res) {
   // create server logic

   getSomeData(client, someDataParser);

   // etc ...
};

http.createServer(createServerCallback);

但是,除非您计划在其他地方重用回调逻辑,否则阅读内联匿名函数通常要容易得多,如您的示例所示.它还将使您不必为所有回调找到名称.

However unless you plan to reuse to callback logic in other places, it is often much easier to read inline anonymous functions, as in your example. It will also spare you from having to find a name for all the callbacks.

另外请注意,正如 @pst 在下面的评论中指出的那样,如果您正在访问内部函数中的闭包变量,以上不会是一个简单的翻译.在这种情况下,使用内联匿名函数更可取.

In addition note that as @pst noted in a comment below, if you are accessing closure variables within the inner functions, the above would not be a straightforward translation. In such cases, using inline anonymous functions is even more preferable.

这篇关于如何避免在 Node.js 中长时间嵌套异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆