Home > Back-end >  How to send Array of WhatsApp messages in a sequence
How to send Array of WhatsApp messages in a sequence

Time:10-27

I am developing a WhatsApp bot using WATI and Node.js

I have an array of messages for eg:

module_split = ["msg 1","msg 2", "msg 3"]

I want to send each element of array one by one in a sequence on WhatsApp. But I am not able achieve that. I tried using setTimeout()

module_split.forEach(msg => {
                    console.log("4. module split ")

                    setTimeout(async () => {
                        await WA.sendText(msg, number).then().catch(e => console.log("Error sending text ", e))
                    }, 30000)

                });

The elements are randomly being sent everytime with different order. I want to send msg 1 first, than msg 2 and so on. Is there a way I achieve this?

Any help or advice is appreciated.

CodePudding user response:

forEach is not suited for async await, also you are mixing await and then. Try with:

for (const msg of module_split) {
  try {
    await WA.sendText(msg, number);
  } catch (e) {
    console.log('Error sending text ', e);
  }
}

CodePudding user response:

You should not use Promise.then() with await and for...of can be used to run asynchronous calls sequentiallly (assuming you do not want to include the delay between messages from your end) using try-catch and await syntax as follows:

for (const msg of module_split)
{
   try {
      console.log("4. module split ")
      await WA.sendText(msg, number)
   } catch (e) {
      console.log("Error sending text ", e)
   }
});
  • Related