Je crée une application dans laquelle un utilisateur peut avoir de nombreuses chambres et chaque chambre peut avoir plusieurs canaux, voici mon code lors de la récupération des chambres et des canaux correspondants:En attente de tâches asynchrones pour terminer nodejs
getRooms: function (req, res) {
User.find({id: req.cookies.claver_id}).exec(function (err, result) {
if (err) {
return res.send(400);
}
rooms = result[0].rooms;
if (rooms.length === 1) {//No room defaults to ['']
return res.send(400);
}
var roomsObj = {};
var roomsArr = [];//we will place the roomsObj inside the roomsArr
var chansObj = {};
var chansArr = [];
async.each(rooms, function (roomId, cb){
roomsObj = {};
if (roomId !== '') {
Rooms.findOne({id: roomId}).exec(function (err, room){
roomName = room.name;
inviteLink = room.inviteLink;
roomsObj.name = roomName;
roomsObj.id = roomId;
roomsObj.inviteLink = inviteLink;
var channels = room.channels;
async.each(channels, function (channelId, cb) {
chansObj = {};
Channels.findOne({id: channelId}).exec(function (err, channel){
chansObj.name = channel.channelName;
chansObj.id = channelId;
chansObj.type = channel.channelType;
chansArr.push(chansObj);
cb();
});
},
function (err) {
});
});
}
cb();
}, function (err) {
roomsObj.channels = chansArr;
roomsArr.push(roomsObj);
sails.log(roomsArr);
});
});
}
Il est supposé retourner un objet javascript avec la structure suivante:
[ { name: "Room Name",
roomId: "Room Id",
inviteLink: "Room Invite Link",
channels: [
{
name: "Channel Name",
id: "channel Id"
}
]
}
]
Mais je reçois toujours un tableau vide parce que async.each(rooms, function (roomId, cb){ })
n'attend pas async.each(channels, function (channelId, cb) {})
pour terminer, j'ai donc objet chambre vide. S'il vous plaît comment puis-je résoudre ce problème?
Clarifiez ce que vous voulez réaliser. Comme je vois que vous voulez "Obtenir toutes les pièces d'un utilisateur et mettre à jour chaque canal attribué à une pièce", non? –
ressemble à un cas pour Promises. – sova
@zabaware oui c'est exactement ce que je veux réaliser. –