使用 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..
  });