0

Below code I have mentioned where i am getting undefined and where i am getting the resul can you help me understand what I am doing wrong.

const Connection=require('../utilities/connection')
let db={}
let data;
db.findall=async()=>{
     Connection.query("select * from offers;", (err, rows, _field) => {
        if (!err) {
            data=rows;
            //console.log(row)---> this give correct output
        }
        else {console.log("Error while fetching");}
    });
    //console.log(data)-->undefined
}
async function run(){
    await db.findall()
    console.log(data);//undefined
}
run()
// module.exports=db
  • Duplicate of [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – esqew Jan 04 '22 at 14:10

1 Answers1

0

Please try to use this example:-

const Connection=require('../utilities/connection')
let db={}
let data;
db.findall=async()=>{
return new Promise(async (resolve,reject) => {
     Connection.query("select * from offers;", (err, rows, _field) => {
        if (!err) {
            resolve(rows)
        }
        else {console.log("Error while fetching");}
        reject(err)
    });
    })
}
async function run(){
    let myAwaitData = await db.findall()
    console.log(myAwaitData);
}
run()

Please i have included the promise to make sure that the data is return to the caller function.

ekibet
  • 176
  • 2
  • 8