0
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.

1
  • Also if i return true/false outside of db.query it will work fine. Is a problem in that db.query. Also if i return true/false without results ... some logic it will behave the same, skip lane and says var a = undefined. Commented Jan 16, 2023 at 13:20

1 Answer 1

1

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();
});
Sign up to request clarification or add additional context in comments.

4 Comments

Works fine with Promise, thanks!!
@Seb. Glad it hepped. You can accept the answer if it works.
u answered so fast that i couldnt accept the answer in less than 10mins as the stackoverflow rulles says
@Seb Oh, that is something I never heard about :\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.