我为我的discord-bot制作了一个功能,在修复和优化代码时遇到了问题。在Promise.all中调用后,函数突然返回undefined。这是有问题的功能:
function setupPlayers(message, tag) {
let opp = tag.toString();
opp = opp.substring(2, opp.length - 1).replace('!', '');
return message.channel.guild.members.forEach((guildMember, guildMemberId) => {
if (guildMemberId === opp) {
const players = [];
const player1 = message.author;
const player2 = guildMember.user;
if (Math.random() > .5) {
players.push(player1, player2);
} else {
players.push(player2, player1);
}
message.channel.send(
`${player1.username} challenged ${player2.username} to a game of tic tac toe!`
);
return players;
}
});
}
这是电话:
Promise.all([
setupPlayers(message, tag),
setupBoard(message, board, buttons)
])
.then(([players, botMessage]) => {
console.log(players);
}
玩家在setupPlayers函数内定义,但在console.log()中未定义。我使用了错误的退货吗?
答案 0 :(得分:0)
通过从forEach循环中删除返回来解决它,将其他return语句移到循环之外并更改它以返回解析promise,如下所示:
return Promise.resolve(players);