Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

62
Views
How to handle async call inside if-condition

given code how to handle async call inside if the condition.not store newname in name and run callback first

var xyz = function (data, callback) {
    try{
        pool.query('select * from devices',[1],function(err,result){ 
            
            if(result.rows[0].name = 12){
                
                pool.query('select * from devices',[12],function(err,result){
                    result.rows[0].name = result.rows[0].newname;
                }
                
            }
            callback(result.rows[0].name);
        });
    }catch(err){
        callback(err);
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Since you tagged async-await, you'll need to use Promise's

So

Create a helper function like this

const promiseQuery = (pool, ...args) => new Promise((resolve, reject) => {
    pool.query(...args, (err, result) => {
        if (err) return reject(err);
        resolve(result);
    });
});

Then use it like this

var xyz = async function (data, callback) {
    try {
        const result = await promiseQuery(pool,'select * from devices', [1]);
        if (result.rows[0].name = 12) {
            const result = await promiseQuery(pool, 'select * from devices', [12]);
            result.rows[0].name = result.rows[0].newname;
            callback(result.rows[0].name);
        }
    } catch (err) {
        callback(err);
    }
}

Of course, some db's already have a promisified version of their functions

So it would be like

var xyz = async function (data, callback) {
    try {
        const result = await pool.query('select * from devices', [1]);
        if (result.rows[0].name = 12) {
            const result = await pool.query('select * from devices', [12]);
            result.rows[0].name = result.rows[0].newname;
            callback(result.rows[0].name);
        }
    } catch (err) {
        callback(err);
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!