Home > Software design >  How to handle async call inside if-condition
How to handle async call inside if-condition

Time:04-20

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);
    }
}

CodePudding user response:

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);
    }
}
  • Related