我是节点js的新手。我有一个部分,我应该得到他们的球队所有球员。
这是代码
var mysql = require("mysql");
var thenJade = require('then-jade');
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 response = [];
var query = connection.query("select * from team", function(err, result, fields) {
for (var index in result)
{
players(result[index].id, function(results) {
callback(result);
});
}
});
}
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);
});
}
但我只从一支球队中获得球员。由于节点js是异步的,它返回一个团队玩家并加载视图。
这是上述代码的控制台输出。
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 89ms - 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' } ]
GET /css/bootstrap.min.css 304 22ms
GET /css/style.css 304 6ms
GET /js/bootstrap.js 304 4ms
GET /js/bootstrap.min.js 304 4ms
GET /css/bootstrap.css 200 32ms - 129.44kb
我来到这里,请帮助。
提前致谢。
答案 0 :(得分:0)
我认为问题出在'团队'功能。回调(结果)是在' for'内部调用的。环。基本上,您在每次迭代时渲染页面。尝试放置回调(结果);在循环之外并将每个团队添加到响应中。
function teams(callback) {
var response = [];
var query = connection.query("select * from team", function(err, result, fields) {
for (var index in result)
{
players(result[index].id, function(results) {
callback(result);
});
}
});
}