简体   繁体   中英

Node.js mysql query rows

app.get('/api/db/:tableName', function(req, res){
    res.setHeader('content-type', 'application/json');
    dbPool.getConnection(function(objErr, objConn){
        if(objErr){
            sendError(res, 503, 'error', 'connection', objErr); //503 - Service Unavailable
        }else{
            var tableName = req.params.tableName;
            console.log(tableName);
            var tRows, bRows;
            var today = moment().format('YYYY-MM-DD 00:00:00');
            var current = moment().format('YYYY-MM-DD HH:mm:ss');
            console.log(typeof today);
            console.log(typeof current);
            if(tableName == 'dashboard'){
                objConn.query("SELECT SUM(taranan) as tTara, SUM(bulunan) as tBul, SUM(resmedilen) as tRes FROM "+tableName, function(Err, Rows, Fields){
                    if(Err){
                        sendError(res, 500, 'error', 'query', Err);
                    }else{
                        tRows = Rows;
                        console.log(bRows);
                    }//else
                });
                objConn.query("SELECT SUM(taranan) as bTara, SUM(bulunan) as bBul, SUM(resmedilen) as bRes FROM "+tableName+" WHERE change_on > '"+today+"'", function(Err, Rows, Fields){
                    if(Err){
                        sendError(res, 500, 'error', 'query', Err);
                    }else{
                        bRows = Rows;
                        console.log(bRows);
                    }//else
                });
                console.log(tRows);
                res.send({
                    results : 'success',
                    err : '',
                    err_type : '',
                    Trows : tRows,
                    Brows : bRows
                });
            }else{
                /* EMPTY ZONE */
            }//else
            objConn.release();
        }//else
    });
});

console.logs work perfect. It get the variables in bRows and tRows but last console.log(tRows) is empty. Because when this line running, mysql have not get datas from db yet. How can i fixed this code?

I know its about asynchronous calling.

What you said is right, the variables aren't populated because the callback have not been executed (no results returned) yet. A quick fix of your code is:

if(tableName == 'dashboard'){
    objConn.query("SELECT SUM(taranan) as tTara, SUM(bulunan) as tBul, SUM(resmedilen) as tRes FROM "+tableName, function(Err, Rows, Fields){
        if(Err){
            sendError(res, 500, 'error', 'query', Err);
        }else{
            tRows = Rows;
            console.log(tRows);

            objConn.query("SELECT SUM(taranan) as bTara, SUM(bulunan) as bBul, SUM(resmedilen) as bRes FROM "+tableName+" WHERE change_on > '"+today+"'", function(Err, Rows, Fields){
                if(Err){
                    sendError(res, 500, 'error', 'query', Err);
                }else{
                    bRows = Rows;
                    console.log(bRows);

                    console.log(tRows);
                    res.send({
                        results : 'success',
                        err : '',
                        err_type : '',
                        Trows : tRows,
                        Brows : bRows
                    });

                }//else
            });

        }//else
    });

}else{

This way both tRows and bRows are already populated when you use them.

Explanation

What the code I gave does:

  • You get the tRows
  • You wait for the result of tRows, then you get the bRows
  • You wait for the result of bRows, then you send the reply back with bRows and tRows

What was happening in your original code:

  • You try to get the tRows
  • You try to get get the bRows
  • You send the reply (without waiting for the results of bRows and tRows)

Promises

You might notice that the nested callbacks looks dirty. A better solution is by using promises. Like bluebird .

A few reminders

Instead of doing a lot of this:

if(Err){
  sendError(res, 500, 'error', 'query', Err);
}else{
  tRows = Rows;
  console.log(bRows);
}//else

You can try returning early:

if (Err) return sendError(res, 500, 'error', 'query', Err);
tRows = Rows;
console.log(bRows);

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM