Zero
Zero

Reputation: 2286

Using a forEach loop to overwrite values

Alright so I have a code like so

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})**`)
    }
  })

Where the commented part returns a promise , I am using a forEach loop and I am aware that we are unable to overwrite values in an asynchronus one therefore my embed returns the portion of the loop without the promise, I am looking for a possible solution to this.

Upvotes: 0

Views: 151

Answers (1)

Yonghoon Lee
Yonghoon Lee

Reputation: 2514

You can use Promise.all with map

Like this

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

Upvotes: 2

Related Questions