Reputation: 85
So I've got a function which is :
module.exports.play = async (client, channel, players) => {
players.push(client.guilds.cache.first().members.cache.array().filter(mem => mem.user.username === "user1").map(mem => mem.user)[0]);
players.push(client.guilds.cache.first().members.cache.array().filter(mem => mem.user.username === "users2").map(mem => mem.user)[0]);
try {
await beginMessage(players, channel);
let playersCards = await beginGame(client, players);
console.log(playersCards);
emitter.on("stop", async () => {
await channel.delete();
console.log("jeu fini");
});
}
catch(e) {
console.error(e);
}
};
and the is that the value of my variable 'playersCards' is print before the value is returned by the async function "beginGame". Here's beginGame's function code :
async function beginGame(client, players) {
let playersCards = [];
fs.readFile("Utils/cartes.json", 'utf8', async (err, data) => {
if(err) console.log(err);
let cartes = JSON.parse(data);
cartes = cartes.cartes;
await asyncForEach(players, async player => {
let playerCards = await distributeCards(player, cartes);
playersCards.push(playerCards);
});
return playersCards;
});
}
Where could the problem be ?
Upvotes: 0
Views: 58
Reputation: 472
Because beginGame
returns a Promise
with no value because fs.readFile
took a callback which is called else where, so there is nothing to wait for.
async function beginGame(client, players) {
return new Promise(async (resolve, reject) => {
let playersCards = [];
return fs.readFile('Utils/cartes.json', 'utf8', async (err, data) => {
if (err) return reject(err);
let cartes = JSON.parse(data);
cartes = cartes.cartes;
await asyncForEach(players, async player => {
let playerCards = await distributeCards(player, cartes);
playersCards.push(playerCards);
});
return resolve(playersCards);
});
});
}
this should work since the function is wrapped with promise and there is something to wait for.
Upvotes: 1