Home > Blockchain >  Node.js async await won't work with db query
Node.js async await won't work with db query

Time:01-17

app.get('/someApi', async (req, res) => {
    var a = await SomeMethod();
})
function SomeMethod() 
{
 let sql = 'SELECT * FROM someTable'
    var query = db.query(sql, (err, results) =>{
        if(err)
        {
            throw err
        }
       if(results ... some logic)
        {
          return true;
        }
       else{
          return false;
       }
    })
}

If i call SomeMethod from someApi it will pass the line and say that var a = undefined instead of true or false. I need to get a response, true/false before going to next line after var a in someApi.

CodePudding user response:

Convert the callback function to a promise and then use await on it.

function SomeMethod() {
    return new Promise((resolve, reject) => {
        let sql = 'SELECT * FROM someTable'
        db.query(sql, (err, results) => {
            if (err) {
                reject(err);
            }
            if (results) {
                resolve(true);
            }
            else {
                resolve(false);
            }
        });
    });
}
app.get('/someApi', async (req, res) => {
    var a = await SomeMethod();
});
  • Related