I am new to nodejs, and I don't properly understand how async functions works. I read about them a lot today, but I cant solve my problem.
I use Sequelize.js as the ORM and my problem is when I nest a query into the callback of an other query then I cant force it to continues only when both query ended.
Here is my current code:
io.on('connection', function (socket) {
socket.on('join', function (data) {
clients[clients.length] = new Client("Client " + clients.length, data.channel);
console.log('Client connected Channel: ' + clients[clients.length-1].channel);
var array = []
DB.Matches.findAll({attributes: ['matchId', 'teamAId', 'teamBId']}).then(function (result) {
for (var i = result.length - 1; i >= 0; i--) {
DB.Teams.findAll({where: { team_id: [result[i].teamAId,result[i].teamBId]}}).then(function (teams) {
array.push({ id: 0, name: teams[0].clubName + ' - ' + teams[1].clubName});
}).then(function () {
// Now my emit event is here but I dont want to run every time the loop run
console.log(array);
socket.emit('matches', array);
});
}
}.then(function () {
// I tried to put it here, but then I got an empty array, because the queries haven't finshed yet
}));
});
});
When this code is called, the array will be emited in every loop with one more element in it in every loop, but this is not good for me. I want to call the emit event once when the array is totally filled.
DB.Matches.findAll({attributes: ['matchId', 'teamAId', 'teamBId']})method. Please read the docs here.module.exports = function (sequelize, Sequelize) { var module = {}; module = sequelize.define('tbl_team', { blablabla }); return module; };