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));
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.
Asynchronous callbacks are functions passed to another function that starts executing code in the background. Typically, when the code in the background finishes, the async callback function is called as a way of notifying and passing on data to the callback function that the background task is finished.
A callback is just a function that's passed into another function, with the expectation that the callback will be called at the appropriate time. As we just saw, callbacks used to be the main way asynchronous functions were implemented in JavaScript.
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With