pfMusk
pfMusk

Reputation: 809

NodeJs run for each loop parallel

i'm currently using this for each loop to fetch data from my mysql database:

//...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));

            });

At the end i wan't to output the object "obj" as JSON with all the required informations.

Thank you very much for your help & sorry for my bad english ;)

Upvotes: 2

Views: 3584

Answers (1)

Kannaiyan
Kannaiyan

Reputation: 13025

Use async.eachSeries instead of async.forEach

Following documentation explains in detail,

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

More examples here,

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

Upvotes: 4

Related Questions