javascript - Node.js - mysql query inside foreach -
i have structure of code:
connection.query(query1,function(err,rows) { var response = []; //doing rows rows.foreach(function(item) { connection.query(queryitem,function(err,rows) { //doing result = rows[0].field; //and want push array response.push(result); }); }); console.log(response); //empty });
i know foreach blocking query non-blocking. tried use promises:
connection.query(query1,function(err,rows) { var response = []; //doing rows rows.foreach(function(item) { var promise = new promise(function(resolve,reject) { connection.query(queryitem,function(err,rows) { //doing result = rows[0].field; //and want push array resolve(result); }); }); promise.then(function(result) { console.log(result); //ok response.push(result) //not ok, result empty }); }); console.log(response); //empty });
but it's not helped. how can push value array non-blocking function , use after?
creating promises step in right direction, need take step further aggregating promises array , passing promise.all, , waiting them finish before trying access response
.
connection.query(query1,function(err,rows) { var response = []; //doing rows promise.all(rows.map(function(item) { var promise = new promise(function(resolve,reject) { connection.query(queryitem,function(err,rows) { //doing result = rows[0].field; //and want push array resolve(result); }); }); return promise.then(function(result) { console.log(result); //ok response.push(result) //ok }); }).then(function () { console.log(response); //not empty }); });
Comments
Post a Comment