skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.)

    const {Connection, Statement} = require('idb-pconnector');
    
    async function get_data(){
    
            const sql_stsmt = 'SELECT * FROM QIWS.QCUSTCDT';        
            const connection = new Connection({ url: '*LOCAL' });
            const stmt = new Statement(connection);
            
            try {
                const x = await stmt.exec('SELECT * FROM QIWS.QCUSTCDT');                
                stmt.close();
                connection.disconn();
                connection.close();            
     
                return x;
            }
            catch (error) {
                return console.error(error);            
                }
        }
    
    async function main() {
        try{
            const result = await get_data()
            console.log("log from function main()");
            console.log("%s", JSON.stringify(result));                
            // now we can present data on web page...
            // ...
        }
        catch(error){
            return console.error(error);            
        }
    }
    
    main();
    

  2. 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.

    let data = main.then(function (result) {
      console.log("%s", JSON.stringify(result)); 
    });
    console.log("3..")     
    // coming out empty {} here.
    
    var async_func = () => {
      var p = new Promise((result) => {
        setTimeout(() => {
          result("foo");
        });
      });
      return p;
    }
    
    var func1 = () => {
      console.log("func1: " + async_func());
    }
    
    var func2 = () => {
      async_func().then((res) => {
        console.log("func2: " + res);
      });
    }
    var func3 = async () => {
      var x = await async_func();
      console.log("func3: " + x);
    }
    
    func3();
    func1();
    func2();
    Login or Signup to reply.
  3. You should wrap exec method
    simple example:

    function execWithCallback(callback: (x: number, err: Error | null) => void) {
      setTimeout(() => {
        callback(1, null)
      }, 1000)
    }
    
    async function execPromise() {
      return new Promise((resolve, reject) => {
        execWithCallback((x, err) => {
          if(err) return reject(err)
    
          return resolve(x)
        })
      })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search