微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 forEach 循环覆盖值

如何解决使用 forEach 循环覆盖值

好的,我有这样的代码

giveaways.forEach( x => {
    if (x.exTradata) {
      const guild = client.guilds.cache.get(x.exTradata.server)
      const channel = guild.channels.cache
        .filter((channel) => channel.type === 'text')
        .first()
      channel.createInvite().then( inv => { // returns promise
     embed.addField(`Join Requirement Giveaway:`,`**[This Server](${inv})**`)
      })
    } else {
      embed.addField(`normal Giveaway:`,`**[${x.prize}](https://discord.com/channels/${x.guildID}/${x.channelID}/${x.messageID})**`)
    }
  })

评论部分返回一个 promise 的地方,我正在使用 forEach 循环,我知道我们无法覆盖异步中的值,因此我的嵌入返回了没有承诺的循环部分,我正在寻找一个可能的解决方案。

解决方法

您可以将 Promise.all 与 map 一起使用

像这样

Promise.all(giveaways.map((x) => new Promise((resolve,reject) => {
  // ~~ doing something
  somePromises.then((inv) => {
    embed.addField(/*~~~*/)
    resolve();
  })
})))
  .then(() => {
    // next things..
  });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。