Async/Await use in NodesJS and Mysql query

Hi guys, i am a bit confused when using Asyc/await, i am basically retrieving the data from the mysql DB and then use the information when constructing an object user_details that i will use later.
I have defined the Asyc function and call right away and then implemented .then to resolve the promise but the promise doesnt seems to get resolved and when i console the Invoice_No_Per_Trasaction it shows as Promise { <pending> } not sure how i can overcome this issue .
Any suggestions guys please. Thanks

let Invoice_No_Per_Trasaction = (async function Invoice_No() {

          connection.query("SELECT invoiceNo FROM  users_basket WHERE users_user_id=?;", [user_id], function (err, results) {

            console.log("107", results); //RowDataPacket { invoiceNo: 1 },. ....

            return results;

          });

        })()

          .then((data) => {

            console.log("112x", data); // undefined

            return data;

          })

          .then((data) => {

            console.log("116", data);  // undefined

            return data;

          });

        console.log("120x", Invoice_No_Per_Trasaction); //Promise { <pending> }

        let user_details = {

          user_FirstName: results[0].first_name, // name

          user_email: userIdentitiy,    // [email protected]

          Invoice_No: Invoice_No_Per_Trasaction,  //Promise { <pending> }

        };

Async functions return promises that resolve to their return value. Your async function, Invoice_No, doesn’t return anything so data in your first then() will be undefined.

Your call to connection.query() has a callback that returns a value, but that only returns from that callback. It doesn’t return from Invoice_No. Invoice_No would need its own return statement. And there’s no way for the callback to return from Invoice_No; it can only return from itself.

If you want the callback value to get returned from Invoice_No, you would need to wrap the call in a promise constructor. That promise can be returned from Invoice_No and the connection.query callback can resolve it.

  async function Invoice_No() {
    return new Promise((resolve, reject) => {
      connection.query("SELECT invoiceNo FROM  users_basket WHERE users_user_id=?;", [user_id], function (err, results) {
        if (err) {
          reject(err);
        } else {
          console.log("107", results); //RowDataPacket { invoiceNo: 1 },. ....
          resolve(results);
        }
      });
    })
  }

Note that at this point, async isn’t necessary for the function. Its only useful for making the function always return a promise (implicitly) and to allow you to use await. But Invoice_No is explicitly returning a promise and not using await so it would still work fine not being async.

1 Like

Thanks senocular.