0

I have a code, where I have a callback, with the value of the callback I send a message on whatsApp. But before the callback loop I add the function of sending a welcome message, however, the welcome message goes after the CallBack message, and it should go before. Does anyone know why it happens and how to solve it?

Code

function start(client) {
  client.onMessage((message) => {
    mensagem = message.body.split(' ')
    estado = mensagem.slice(1, 2)
    palavraChave = mensagem.slice(0, 1).join(' ').toLowerCase()
    NomePessoa = message.sender.name || message.sender.pushname
    if (palavraChave === '/coronavírus' || palavraChave === '/coronavirus') {
      client.sendText(message.from, `Hello`) //This message goes last
      api.pesquisa(`${estado}`).then((infoCorona) => {
        client.sendText(message.from, `${infoCorona}`) //This message goes first
        contador++
        console.log(`Você ajudou ${contador} pessoas.`)
      });
    }
  });
}
Phil
  • 157,677
  • 23
  • 242
  • 245
  • So you're saying that `Hello` should be sent first but is actually sent _after_ `infoCorona`? What library are you using? Is it [wa-automate](https://www.npmjs.com/package/@open-wa/wa-automate)? – Phil Oct 16 '20 at 01:59
  • Assuming it is wa-automate, `sendText` returns a promise. You should wait for that to resolve. See the examples in their documentation ~ https://www.npmjs.com/package/@open-wa/wa-automate#usage – Phil Oct 16 '20 at 02:02
  • Im using Venom-bot – Matheus Nascimento Oct 16 '20 at 02:36
  • Same approach. `sendText` returns a promise so either `await` it or append a `.then()` callback to send your second message – Phil Oct 16 '20 at 02:38
  • How can I do this? Sorry, I'm studying JS etc so I'm lost;) – Matheus Nascimento Oct 16 '20 at 02:44
  • Make your `onMessage` callback `async` by changing it to `client.onMessage(async (message) => {` then change the _hello_ message line to `await client.sendText(message.from, "Hello")` – Phil Oct 16 '20 at 02:46

0 Answers0