I am trying to call function that makes SQL call and returns the data to the calling function
I am trying unsuccessfully to use async/await (promises) syntax in node.js/javascript
My function is still behaving asynchronously.
Perhaps not quite understanding how this is supposed to work.
See notes in code
const {dbconn, dbstmt} = require('idb-pconnector');
async function get_data(){
const {dbconn, dbstmt} = require('idb-connector');
const sql_stsmt = 'SELECT * FROM QIWS.QCUSTCDT';
const conn1 = new dbconn();
conn1.conn('*LOCAL');
const stmt = new dbstmt(conn1);
try {
await stmt.exec(sql_stsmt, (x) => {
stmt.close();
conn1.disconn();
conn1.close();
// getting expected data here..
console.log("1..")
console.log("%s", JSON.stringify(x));
return x;
});
}
catch (error) {
return console.error(error);
}
}
async function main() {
try{
const result = await get_data()
console.log("2..")
// still coming out undefined here...
console.log("%s", JSON.stringify(result));
return result;
}
catch(error){
return console.error(error);
}
}
let data = main();
console.log("3..")
// coming out empty {} here.
console.log("%s", JSON.stringify(data));
3
Answers
Lots of good ideas and readings. Thanks to Keith and and VLAZ was able to revise. Works now. (But, still may need some help with error trapping logic.)
What you are trying to do cannot be done in JavaScript.
=== edit ===
It can be done, but it still must be done in an asynchronous function.
async and await
do not fundamentally change how promises work in JavaScript, nor it being single threaded.Async functions return a Promise, and the only way to get the results of this promise in a non-async function is by calling
then
on the promise.You should wrap exec method
simple example: