【问题标题】:Any better solution about asynchronous query form main table and sub table?关于异步查询表单主表和子表有更好的解决方案吗?
【发布时间】:2014-06-30 15:48:25
【问题描述】:

我有两个表,tb_article 和 tb_attach_url,像这样

==============tb_article=================
id      title       content
1       "echo"      "test"
2       "foo"       "bar"

==============tb_attach_url==============

id      article_id      url_val
1       2               "http://.../foo.png"
2       2               "http://.../bar.png"
3       1               "http://.../test.png"

我的场景是这样的, 我想显示 tb_article 的列表, 但是tb_attach_url的信息也需要。

我的解决办法是这样的:

function load_article_urls(id, idx, callback){
    connection.query("select url_str from tb_attach_url where article_id = ?", [id], function(err, results){
        if (err) throw err;

        var images = [];
        for (var j = 0; j < results.length; j++){
            images.push(results[j]["url_str"]);
        }
        callback(idx, images)
    });
}

function load_article(req, res){
    connection.query('select * from tb_article where id = ?', [req.query.id], function(err, results){
        if (err) throw err;

        var cnt = 0;
        for (var i = 0; i < results.length; i++){

            load_article_urls(results[i].id, i, function(idx, urls){

                results[idx]["urlset"] = urls;

                cnt++;
                if (cnt == results.length){
                    //waiting for all back
                    res.render('list_article', { article_list: results});
                }
            });
        }
    });
}

我觉得这个工具有点丑,想知道一些更好的方法。 感谢您的帮助。

【问题讨论】:

    标签: node.js asynchronous express node-mysql


    【解决方案1】:

    你可以使用async.map (GitHub) 来做这样的事情:

    async.map(results,
      function (err, callback) { /* Call callback with the urls as a parameter here */ },
      function (err, allUrls) {
        // Combine results and allUrls - they are in the same order.
    })
    

    或者使用async的其他一些功能来达到类似的效果。

    【讨论】:

      猜你喜欢
      • 2010-11-08
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多