gpt4 book ai didi

javascript - NodeJs 为每个循环并行运行

转载 作者:搜寻专家 更新时间:2023-11-01 00:37:34 26 4
gpt4 key购买 nike

我目前在每个循环中使用它从我的 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。

非常感谢您的帮助,抱歉我的英语不好 ;)

最佳答案

Use async.eachSeries instead of async.forEach

下面的文档有详细解释,

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

这里有更多例子,

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

关于javascript - NodeJs 为每个循环并行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46147240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com