Page loads without query finish - Nodejs + Mysql

Asked

Viewed 24 times

-1

I need the page to render only when the query returns some value, I tried to use Promise, async, await... but nothing seems to work, the page always renders and then the data is retrieved.

controller:

    var conn = app.config.connection();
    var bankModel = new app.app.models.bank_model;
    var capitalMc;

    bankModel.valor_total(conn, function(error, result){
        if(error){
            console.log(error);
            res.send(error);
            return;
        }else if(Object.keys(result).length > 0){
            console.log('result' + formatNumber(result[0].valor_total));
            capitalMc = formatNumber(result[0].valor_total);
        }else{
            capitalMc = 'Erro ao carregar os dados.';
            console.log("Erro ao carregar os dados.")
        }
    })
    res.render('template', {title: 'Painel de controle', body: 'dashboard_view', bodyclass: '', capitalMc: capitalMc});

model:

function bank_model(){

}

bank_model.prototype.valor_total = function(conn, callback){
    var sqlQuery = "SELECT valor_total FROM bank";
    conn.query(sqlQuery, callback);
}

module.exports = function(){

    return bank_model;
}

I don’t know if it’s a recommended way or if there’s something wrong, but nothing works! kk

  • you ever tried to make bank_model.prototype.valor_total = async function(conn, callback) { await conn.query(sqlQuery, callback) } and call with await bankModel.valor_total(conn,.....)? (remember that your controller function needs to be async tb)

1 answer

0

I believe you are using express. But if you are using another framework, the result is the same.

You call "res.render" before the callback returns. Although the call for "res.render" came at the end, the callback can return well after.

Correction:

    bankModel.valor_total(conn, function(error, result){
        if(error){
            console.log(error);
            res.send(error);
            return;
        }else if(Object.keys(result).length > 0){
            console.log('result' + formatNumber(result[0].valor_total));
            capitalMc = formatNumber(result[0].valor_total);
            res.render('template', {title: 'Painel de controle', body: 'dashboard_view', bodyclass: '', capitalMc: capitalMc});
        }else{
            capitalMc = 'Erro ao carregar os dados.';
            console.log("Erro ao carregar os dados.")
            res.render('template', {title: 'Painel de controle', body: 'dashboard_view', bodyclass: '', capitalMc: capitalMc});
        }
    })

OBS: use Return, just as you are using, has no effect, take a moment to think about it!

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.