Reputation: 11
I have this structure of code:
connection.query(query1,function(err,rows) {
var response = [];
//doing something with rows
rows.forEach(function(item) {
connection.query(queryItem,function(err,rows) {
//doing something
result = rows[0].field;
//and want to push it to an array
response.push(result);
});
});
console.log(response); //empty
});
I know that forEach is blocking but query is non-blocking. I tried to use promises:
connection.query(query1,function(err,rows) {
var response = [];
//doing something with rows
rows.forEach(function(item) {
var promise = new Promise(function(resolve,reject) {
connection.query(queryItem,function(err,rows) {
//doing something
result = rows[0].field;
//and want to push it to an array
resolve(result);
});
});
promise.then(function(result) {
console.log(result); //ok
response.push(result) //not ok, result is empty
});
});
console.log(response); //empty
});
But it's not helped. How can I push value into array from non-blocking function and use it after?
Upvotes: 1
Views: 4984
Reputation: 95017
Creating promises is a step in the right direction, but you need to take it a step further by aggregating the promises into an array and passing to Promise.all, and then waiting for them all to finish before trying to access response
.
connection.query(query1,function(err,rows) {
var response = [];
//doing something with rows
Promise.all(rows.map(function(item) {
var promise = new Promise(function(resolve,reject) {
connection.query(queryItem,function(err,rows) {
//doing something
result = rows[0].field;
//and want to push it to an array
resolve(result);
});
});
return promise.then(function(result) {
console.log(result); //ok
response.push(result) //ok
});
}).then(function () {
console.log(response); //not empty
});
});
Upvotes: 4