Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading