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

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

问题描述

我想打,从数据库显示一些数据的页面,所以我创造了一些函数得到从我的DB数据。我只是在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 ...
});

可以改写看起来是这样的:

Could be rewritten to look something like this:

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 在评论中指出的下面,如果你正在访问的内部函数内封变量,上述将不是一个简单的转换。在这样的情况下,使用内联匿名功能则更是preferable。

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天全站免登陆