8

I'm new to asynchronous programming, I'm facing issue similar to this question, in this question suggested approach uses callbacks but I'm trying to do it using Promises and async-await functions. I get undefined in the console. Here's my example. what am I missing?

 //Defining the function
 async query( sql, args ) {
    const rows = this.connection.query( sql, args, async( err, rows ) => 
     { 
        if ( err )
           throw new Error(err); 
        return rows; 
      } );
}

//calling the function here 
 db.query("select 1")
 .then((row) => console.log("Rows",row)) // Rows undefined
 .catch((e) => console.log(e));
Maryam Dairkee
  • 137
  • 1
  • 6
  • 1
    What you're missing is `await`. – Pointy Jan 30 '18 at 14:55
  • 1
    You don't put `async` on a callback function. You use the Promise constructor, and then you use `await` instead of `then` when you're calling the function. – Bergi Jan 30 '18 at 15:04

1 Answers1

7

make your query function return a Promise

function query(sql, args) {
    return new Promise(function (resolve , reject) {
        this.connection.query(sql, args, (err, rows) => {
            if (err)
                reject(err);
            else
                resolve(rows)
        });
    });
}


//calling the function here 
query("select 1")
.then((row) => console.log("Rows",row)) // Rows undefined
.catch((e) => console.log(e));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
  • 2
    This works, but can't we do it using async and await in query function? – Maryam Dairkee Jan 31 '18 at 06:22
  • 1
    If you really wanted to use async/await inside the outside query function, you could "await new Promise(...)". Regardless, you still need a Promise to convert the callback whether you use async/await or just plain Promises. – Aaron Tribou Aug 07 '18 at 02:29