How to solve this problem?

Good day!
Faced with such a problem as synchronous and asynchronous execution of your code, understand how it works, but don't know how to implement.
return new Promise(function(resolve, reject) {

 var array = [];
 // Make a query to a table
 connection.query(" SELECT * FROM `tb_1` WHERE `id`=? ", [id], function(error, result) {
 ... // Do check and output the result as an array
 // Next, I want to iterate through the array to write it to the individual type in a NEW array
 for (var i in result) {
 // Begin search and sort records into a NEW array by type
 switch (result[i]) {
 case 'type_1':
 array[result[i].id] = {
 'type_1': {}
};
break;
 case 'type_2':
 // NOTE
 // And suddenly I need to compare the value of the total type with the other table!
 // I'm doing a query to another table 
 connection.query(" SELECT * FROM `tb_2` WHERE `id`=? ", [id], function(error, result_2) {
 ... // Do I need validation add to the array a new entry to this type of table tb_2
 array[result[i].id] = {
 'type_2': {}
};
})
break;
}
}
 //And since it is all Promise, I'll return promise
 resolve(array) // And here there are troubles, as I was doing an asynchronous request to tb_2 records type_2 not recorded in array

})
})

How to be in this situation?
April 4th 20 at 13:01
1 answer
April 4th 20 at 13:03
Solution
It is possible that connection.query from Your library already knows how to work with Promise, but if not, then you can wrap it using the built-in functions util.promisify:
const {promisify} = require('util');
const query = promisify(connection.query.bind(connection));


And then everything is easily solved with the help of async/await:
getSomethingFromDB async function() { // don't know what name You have in the original
 const result = await query(" SELECT * FROM `tb_1` WHERE `id`=? ", [id]);
 const array = [];
 for (var i in result) {
 // ...
 const result_2 = await query(" SELECT * FROM `tb_2` WHERE `id`=? ", [id]);
 // ...
}
}

PS I'd even iterators have used (.map in particular) and the result would be returned via a Promise.all
Thank you so much! - werner64 commented on April 4th 20 at 13:06

Find more questions by tags Node.js