You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在执行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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:33:30