Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

71
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda