如何在执行Promise结果时忽略空值并保留有效结果?
解决思路与代码优化方案
针对你遇到的问题,核心是处理Promise返回的undefined值,避免展开数组时报错,同时保留有效结果,具体实现方案如下:
1. 将undefined转换为空数组
在每个Promise调用后,通过.then()将undefined替换为空数组,这样后续展开操作不会因undefined报错:
async sendFreeGames(channels) { // 对每个Promise的结果做兜底处理,undefined转为空数组 const [epicGames, steamGames, epicButtons, steamButtons] = await Promise.all([ this.createEpicFreeGamesEmbeds().then(res => res ?? []), this.createSteamFreeGamesEmbeds().then(res => res ?? []), this.createEpicFreeButtons().then(res => res ?? []), this.createSteamFreeButtons().then(res => res ?? []) ]); // 合并有效结果,空数组不影响最终合并结果 const games = [...epicGames, ...steamGames]; const buttons = [...epicButtons, ...steamButtons]; if (games.length === 0) return; // 提前创建axios实例,避免循环内重复创建 const discordAxios = axios.create({ baseURL: 'https://discord.com/api/v10', headers: { Authorization: `Bot ${process.env.DISCORD_TOKEN}` }, }); for (const channel of channels) { // 建议添加错误捕获,避免单个请求失败导致整个流程中断 try { await discordAxios.post(`/channels/${channel.data.id}/messages`, { embeds: games, components: [{ type: 1, components: buttons }] }); } catch (err) { console.error(`发送消息到频道${channel.data.id}失败:`, err); } } }
2. 额外优化点
- 使用
await替代.then()链式调用,代码更易读,符合async函数的写法规范 - 把axios实例创建移到循环外,避免重复创建实例,提升性能
- 添加请求错误捕获,防止单个频道发送失败导致后续流程终止
- 解构赋值直接获取每个Promise的结果,代码更清晰
原理说明
res ?? []是ES2020的空值合并运算符,当res为undefined或null时,会返回空数组。这样即使某个方法返回undefined,合并数组时也只会合并空数组,不会影响最终的有效结果,同时所有Promise都会被执行完毕。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

