我有这样一段代码,它执行一个函数来承诺4个公共方法,公共方法有代码来返回什么,如果他们不满足一定的条件。如果其中一个结果是空的(未定义),我希望它忽略该结果,但仍然保留并执行其他结果。任何人都有一个想法,如何做到这一点或解决它?
async sendFreeGames(channels) {
Promise.all([this.createEpicFreeGamesEmbeds(), this.createSteamFreeGamesEmbeds(), this.createEpicFreeButtons(), this.createSteamFreeButtons()]).then(
(results) => {
const games = [...results[0], ...results[1]];
const buttons = [...results[2], ...results[3]];
if (games.length === 0) return;
for (const channel of channels) {
// @ts-ignore
const discordAxios = axios.create({
baseURL: 'https://discord.com/api/v10',
headers: { Authorization: `Bot ${process.env.DISCORD_TOKEN}` },
});
discordAxios.post(`/channels/${channel.data.id}/messages`, { embeds: games, components: [{ type: 1, components: buttons }] });
}
},
);
}
}
2条答案
按热度按时间wlp8pajw1#
你好像在找
根据这些函数返回的确切内容,您可能不需要
?? []
,也可能不需要.filter(Boolean)
。您可能还需要以相同的方式处理buttons
。toe950272#
要忽略结果中的
undefined
或null
值,您可以在解构之前提供一个默认(即空)数组或(如果结果中有多个数组,并且希望为所有数组提供
[]
)但实际上,如果方法返回空数组而不是
undefined
,则更简洁此外,您当前定义函数的方式,即
任何调用你的函数
foobar
的人将继续 * 的方式之前 * 您的
Promise.all()
解决。要么
或