async function bringData() {
return new Promise(resolve => {
setTimeout(() => {
resolve(con.query('SELECT company, industry FROM my_table', function (err, result) {
if (err) {
console.error(err);
throw 'Error getting data from google_businesses table';
} else {
return result;
}
}));
}, 1000);
});
}
(async () => {
// return data from brindData function
let getData = await bringData();
console.log(getData);
})();
I am calling this function in main but I am always getting error. I am kind of new to node so if please anybody can guide me or is there any other way to do this such that when I have got my result I can return it.
CodePudding user response:
Call resolve
with the result
from your query.The con.query
looks like another asynchronous thing:
con.query('...', (err, result) => {
if (!err)
resolve(result);
});
CodePudding user response:
You can try this.
async function bringData() {
return new Promise((resolve, reject) => {
con.query('SELECT company, industry FROM my_table', (err, result) => {
if (err) {
reject(err);
}
resolve(result);
})
});
}
(async () => {
// execute bringData function
try {
let getData = await bringData();
console.log(getData);
} catch (e) {
console.error(e);
}
})();