Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside async function, returning value from a callback function returns Promise(undefined) [duplicate]

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));
like image 630
Maryam Dairkee Avatar asked Jan 30 '18 14:01

Maryam Dairkee


People also ask

Can an async function return a value?

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.

Can we use async in callback?

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.

What is callback in async?

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.

Why is await returning a promise?

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.


1 Answers

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));
like image 93
Ali Faris Avatar answered Oct 17 '22 07:10

Ali Faris