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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -