简体   繁体   中英

How to fetch complete data from mysql in nodejs callbacks function

 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); }); } 

I am trying to group the data of a particular team with team players. And i'm getting partial output. But if i use console.log(), i am able to see the entire output in console

Output in console looks like this.

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' } ]

Only team id with 1 is appearing in jade view.

And is the procedure followed is correct. I am new to node js.

Thanks in advance:)

This is because you are sending the response after you receive the first callback, ie, the team1 results and before you receive the other two, the 2nd and 3rd team results.

In function teams(), use

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

instead of just

callback(results);

inside the for loop.

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