There are too many approaches to solve your problem.
No doubt the best one is using promises (but you should learn a bit about them before). There are a lot or resources in the net explaining it. Some better and some poorer.
There is a really good and extense explanation about that in the Async and Performance book. But, sure, you could find shorter howto's in the net.
On the other hand, if you are only searching for a fast and simple (but not as escalable and elegant) solution, can simply check for the fullfillment (Oh! this is a promise concept!) of the array in the query handler clalback:
if (j == somArr.lengt - 1) {
console.log(output)
};
...Or a little bit less dirty approach: Unconditionally call some predefined function like:
function checkLast() {
if (output.length >= someArr.length) {
console.log(output);
};
};
Edit: If you would try, using promise should look like this (untested). But it could depend on the exact implementation library:
var tasks;
for (var j = 0; j < someArr.length; j++) {
tVal = someArr[j]; //some manipulation of someArr[i]
tasks.push(new Promise(function(resolve, reject) {
connection.query("select id from someTable where someCol = ?", val, function (err, rows, fields) {
if (err) {
reject(err);
} else {
resolve(rows[0].someVal);
}
});
}));
}
Promise.all(tasks)
.then(function(data) {
console.log(data);
})
.catch(function(err){
console.log(err);
});