'How to split and post several messages for Discord

Discord's 2000 character limit is the most unwelcome restriction, judging from its user feedback, so I have to break up my message in chunks, and send them one by one. However, I'm blocked at the last step.

My sendMessage calls the Discord's send method:

function sendMessage(chanID, msg) {
  return discordbot.channels.cache.get(chanID).send(msg)
}

And I've already broken down the long text into an array called part. This is how I'm trying to send them:

  if (msg.length < 2000) {
    return sendMessage(chanID, msg)
  }

  . . . 

  parts.map(async function(part) {
    return await sendMessage(chanID, part)
  })

The first part is working but obviously the last part is not, as my function should return Discord's send method eventually, which is a promise, and the last loop is not.

However, I don't know nodejs/promise well enough to fix it myself. Adapting from the answer from https://stackoverflow.com/a/24985483/2125837, here is my take:

function sendAll(chanID, parts) {
    return parts.reduce(function(promise, msg) {
        return promise.then(function() {
            sendMessage(chanID, msg)
        });
    }, Promise.resolve());
}

Please help.



Solution 1:[1]

If you replace your map function with the following, it will likely work. I haven't actually tested the code.

parts.reduce(function(promise, part) {
  return promise.then(function() {
    return sendMessage(chanID, part)
  });
}, Promise.resolve());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1