The best pattern for handling async looping in Node.js

前端 未结 3 571
有刺的猬
有刺的猬 2021-01-03 00:01

I\'m new to Node and trying to ensure that I\'m using sane designs for a JSON-driven web app.

I\'ve got a bunch of data stored in Redis and am retrieving it through

3条回答
  •  忘掉有多难
    2021-01-03 00:27

    but I can't help thinking that the i == replies.length-1 is a little untidy?

    I've heard a lot of people say that. This is how I would do it by hand:

    app.get("/facility", function(req, res, next) {
      rc.keys("FACILITY*", function(err, replies) {
        if (err) return next(err);
        var pending = replies.length;
        res.write("[");
        replies.forEach(function (reply) {
          rc.get(reply, function(err, reply) {
            res.write(reply);
            if (!--pending) {
              res.write("]");
              return res.end();
            }
            res.write(",");
          });
        });
      });
    });
    

    Obviously doing it by hand isn't too pretty, which is why people have it abstracted into a library or some other function. But like it or not, that is how you do an async parallel loop. :)

    You can use the async library mentioned before to hide the nasty innards.

提交回复
热议问题