简体   繁体   中英

How to resolve promises in order?

I'm having a very troublesome time figuring out how to do promises in order. I'm making a chat bot for DiscordApp in Node.js, I have searched plenty on here and Google in general. I've tried using Promise.all and a Async function. They have not worked, but I feel I'm doing something wrong.

Currently am back to where I started with my code

let emoji = ['1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣']

msg.channel.send('some message being sent')
  .then(sentMessage => {
    poll.users[msg.author.id].forEach(function(item, index) {
      sentMessage.react(emoji[index])
    })
  })

This leads to the reactions on the message sometimes, if not most times, being mixed up. As you can see, the emojis are numbers, so I'd like them to be in sequential order. Since .react() is a promise, they randomly resolve so as I said before, the numbers emojis get mixed up. If I was wanting them to resolve in order, how could I do this?

Things I've tried: Promise.all

msg.channel.send('some message being sent')
  .then(sentMessage => {
    foo(poll, msg, sentMessage, index)
  })

async function foo(poll, msg, embedded, voteCount) {
  return await Promise.all(poll.users[msg.author.id].map(() => {
    embedded.react(nums[voteCount])
  }))
}

Maybe you want to try this:

msg.channel.send('some message being sent')
  .then(sentMessage => {
    const result = poll.users[msg.author.id].reduce((p, c, i) => p.then(() => sentMessage.react(emoji[i])), Promise.resolve());

    result.then(() => {
        console.log('all emojis shall be sent in order');
    });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM