Martin Schoonbeek Martin Schoonbeek - 4 months ago 35
Javascript Question

How to Async combine multiple JSON arrays into 1 with Node.js javascript

I'm using NodeJS and Async to perform multiple select queries. Therefore I want to populate the

collection
array with
firstqueryarray
and
secondqueryarray
.

How can I combine the first and second response into one array?

exports.relations = function (req, res) {

var collection = [];

async.parallel([
function () {
var firstqueryarray= [];
connection.query(query1, function (err, rows, fields) {
if (err) throw err;
for (var i in rows) {
firstqueryarray.push({
name: rows[i].name,
email: rows[i].email
});
}
res.json({
firstqueryarray: firstqueryarray
});
});

}

, function () {
var secondqueryarray= [];
connection.query(query2, function (err, rows, fields) {
if (err) throw err;

for (var i in rows) {
secondqueryarray.push({
name: rows[i].name,
email: rows[i].email
});
}
res.json({
secondqueryarray: secondqueryarray
});
});
}
]
)
};

Answer

You might consider the conventional camelCase here (i.e., secondQueryArray as a variable name).

async.parallel will execute all functions in the array passed as its first argument one after the other rapidly, and once all have returned, execute the second function passed to it.

Therefore:

You currently have your two functions done oddly (one inside the array, one outside and passed as a second argument). Instead of one inside the array, and one outside the array, you should have both of the functions you have in the array. Both of the functions in the array should have their res.json() calls replaced with collection.push() calls. Then, as your second argument to async.parallel, you should have a function (which will execute after all calls in the array have finished) that executes res.json(collection).

exports.relations = function (req, res) {

    var collection = { collection:[] };

    async.parallel([
        function () {
            var firstQueryArray= [];
            connection.query(query1, function (err, rows, fields) {
                if (err) throw err;
                for (var i in rows) {
                    firstQueryArray.push({
                        name: rows[i].name,
                        email: rows[i].email
                    });
                }
                collection.collection.push(firstQueryArray);
            });

        },
        function () {
            var secondQueryArray= [];
            connection.query(query2, function (err, rows, fields) {
                if (err) throw err;

                for (var i in rows) {
                    secondQueryArray.push({
                        name: rows[i].name,
                        email: rows[i].email
                    });
                }
                collection.collection.push(secondQueryArray);
            });
        }],
        function() {
            res.json(collection);
        }
    )
};