(Thanks to user jfriend00 for pointing out a major oversight in my original answer)
If conn.query
is returning a promise then you could make this work in the manner you are describing by using async
/await
:
async function getProducts() {
var SelectQuery = "Select * FROM `products`";
var ProductDetails = {};
await conn.query(SelectQuery, function(err, result) {
if (err) {
console.log(err);
} else {
ProductDetails = result;
}
});
console.log(ProductDetails);
}
But note this only works if your conn.query
returns a promise. Also, it is a newer ES feature, so you may need to transpile it depending on your node version. Also, note that the function this takes place in will need to be wrapped with async
.
Otherwise, the other candidates to leverage for handling asynchronicity are callback functions and Promises.
If conn.query
does not return a promise, you could write your own query implementation that would return a promise so you could leverage async
/await
:
function asyncQuery(sqlQuery) {
return new Promise((resolve, reject) => {
conn.query(SelectQuery, function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
})
})
}
Then the original function could be rewritten as:
async function getProducts() {
var SelectQuery = "Select * FROM `products`";
var ProductDetails = await asyncQuery(SelectQuery);
console.log(ProductDetails);
}