节点Mysql异步多个查询 [英] Node Mysql async multiple queries

查看:65
本文介绍了节点Mysql异步多个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道处理嵌套mysql查询的最佳方法是nodejs.

I was wondering what's the best way to handle nested mysql-queries is nodejs.

是这样的:

connection.query("SELECT * FROM blogs ORDER BY time DESC", function(err, blogs, fields) {

   for (blog in blogs) {

        connection.query("SELECT * FROM tags WHERE blog_id='blog.id' ", function(err, tags, fields) {

        blog.tags = tags

     });

   }

   res.send(blogs)

});

由于异步特性,这显然行不通.在获取标签之前,结果已经返回.

This obviously doesn't work, because of the async nature. The result already gets returned before the tags are fetched.

我一直在阅读有关节点和回调的信息,promise似乎是要走的路.但是我看不到如何在这个小例子中最好地使用它们.

I've been reading up on node and callbacks and promises seems to be the way to go. But I'm unable to see how I would best use them in this small example.

谢谢!

推荐答案

因此,在发送响应之前,您必须等待所有回调返回.如果我们为简单起见忽略了错误处理并清空了结果,则可以执行以下操作:

So you have to wait for all callbacks to return before you send the response. If we ignore error handling and empty results for simplicity this can be done similar to:

var callback = function(blogs) {
    res.send(blogs);
}

connection.query("SELECT * FROM blogs ORDER BY time DESC", function(err, blogs, fields) {
    var pending = blogs.length;

   for (blog in blogs) {

        connection.query("SELECT * FROM tags WHERE blog_id='blog.id' ", function(err, tags, fields) {
        blog.tags = tags;

        if (0 === --pending) {
            callback(blogs);
        }
     });
   }
});

有了promise,请查看Promise.all函数,该函数将返回新的promise.当数组中传递给它的所有承诺均得到解决时,此承诺即得到解决.使用Q库,它应该类似于:

With promises, look into Promise.all function which returns a new promise. This promises is resolved when all promises passed to it in the array are resolved. With the Q library it should be something like:

var getTags = function(blog) {
    var deferred = Q.defer();
    connection.query("SELECT * FROM tags WHERE blog_id='blog.id' ", function(err, tags, fields) {
        blog.tags = tags;
        deferred.resolve();
    });
    return deferred.promise;
}

var promises = blogs.map(getTags(blog));

Q.all(promises).then(res.send(blogs));

这篇关于节点Mysql异步多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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