如何在nodejs回调函数中从mysql中获取完整数据

时间:2015-07-25 10:53:18

标签: mysql node.js express pug



var mysql = require("mysql");
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'nodejs'
});

exports.players_list = function(req, res) {
    
    var data = {title: "", res: {}};
    if (authenticate(req, res)) {

        results_aaa(function(result) {
            console.log(result);
            res.render('players/players', {title: 'Players List', res: result});
        });
    } else {
        req.session.error = 'Please login to continue.';
        res.redirect('/login');
    }
};

function results_aaa(callback) {
    teams(function(res) {
        callback(res)
    });
}

function teams(callback) {
    var query = connection.query("select * from team", function(err, result, fields) {
        for (var index in result)
        {
            players(result[index].id, function(results) {
                callback(results);
            });
        }
    });
}

function players(id, callback) {
    query("SELECT * FROM players where team = " + id, function(results) {
        callback(results);
    });
}

function query(sql, callback) {
    connection.query(sql, function(error, results, fields) {
        callback(results);
    });
}




我正在尝试将特定团队的数据与团队成员分组。 而且我得到了部分输出。但是如果我使用console.log(),我可以在控制台中看到整个输出

控制台中的输出如下所示。

Express server listening on port 8081
[ { id: 2, player_name: 'Virat Kohli', team: '1' },
  { id: 4, player_name: 'A B DeVilliers', team: '1' },
  { id: 6, player_name: 'Chris Gayle', team: '1' } ]
GET /players 200 162ms - 638
[ { id: 7, player_name: 'Ajinkya Rahane', team: '2' },
  { id: 8, player_name: 'Shane Watson', team: '2' },
  { id: 9, player_name: 'Stuart Binny', team: '2' },
  { id: 10, player_name: 'Karun Nair', team: '2' },
  { id: 11, player_name: 'Sanju Samson', team: '2' } ]
[ { id: 1, player_name: 'Virender Sehwag', team: '3' },
  { id: 3, player_name: 'David Miller', team: '3' },
  { id: 5, player_name: 'Shaun Marsh', team: '3' } ]

只有1的团队ID出现在玉视图中。

并且遵循的程序是正确的。我是节点js的新手。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

这是因为您在收到第一个回调后发送回复,即team1结果,在您收到其他两个回合之前,即第2和第3个团队结果。

在功能团队()中,使用

  

if(index == result.length-1){callback(results); }

而不仅仅是

  

回调(结果);

for循环内。