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));
2
  • 1
    What you're missing is await. Commented Jan 30, 2018 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. Commented Jan 30, 2018 at 15:04

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

2 Comments

This works, but can't we do it using async and await in query function?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.