NodeJs run for each loop parallel

312
September 11, 2017, at 10:48 AM

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

Answer 1

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/

Rent Charter Buses Company
READ ALSO
Selecting null: what is the reason of using selectAll(null) in D3.js?

Selecting null: what is the reason of using selectAll(null) in D3.js?

I've seen some D3 codes with a pattern like this for appending elements:

258
Retrieval of events Google calendar

Retrieval of events Google calendar

I am resurrecting a previous thread located here google api events list

305
Loading Ajax Data Dynamically

Loading Ajax Data Dynamically

I have a bunch of jQuery functions which gets JSON data from a MySQL database and displays it on certain pages within my application

291
How to store div content to DB?

How to store div content to DB?

In my project, sheet processing data will be append to a timeTagDiv div(just like A and B are talking, and the content will show in the dialog)The new message send to dialog will append to timeTagDiv div

270