NodeJs为每个循环并行运行

时间:2017-09-11 01:57:48

标签: javascript mysql node.js database ecmascript-6

我目前正在为每个循环使用它来从我的mysql数据库中获取数据:

//...sql query returns result

var obj = {};
Object.assign(obj, result);

async.forEach(obj, function (item, callback){
                switch(item.type){
                    case 11:
                        //for example counting likes
                        db.query("SELECT COUNT(*) AS likes FROM tbl_post_likes WHERE BINARY post_id = ?", [item.post_id], function(err, res){
                            if(err) throw err;

                            item.likes = res[0].likes;
                            callback();

                        });
                        break;
                    case 12:

                        /*I haven't completed the other types yet.
                          But they are having similar queries
                          because there are different kind of posts.
                          I want to to run these queries parallel */

                        callback();
                        break;
                    case 21:
                        callback();
                        break;
                    case 22:
                        callback();
                        break;
                    default:
                        console.log("wtf?: " + result[i]);
                        callback();
                        break;
                }

            }, function(err) {
                if(err) throw err;
                res.writeHead(200, {"Content-Type": "application/json"});
                console.log(obj);
                res.end(JSON.stringify(obj));

            });

最后我不想输出对象" obj"作为带有所有必需信息的JSON。

非常感谢你的帮助和帮助。抱歉我的英语不好;)

1 个答案:

答案 0 :(得分:3)

  

使用async.eachSeries而不是async.forEach

以下文档详细说明,

https://caolan.github.io/async/docs.html#eachSeries

此处有更多示例,

http://wirama.web.id/node-js-array-looping-with-async/