# Async function for sending messages (CHATBOT)

**URL:** <https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403>\
**Category:** General\
**Created:** [28 January 2022 12:42 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403 "2022-01-28T12:42:56Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![wjr1506](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/wjr1506/32/50619_2.png) [@wjr1506](https://discourse.nodered.org/u/wjr1506)\
**Post date:** [28 January 2022 12:42 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/1 "2022-01-28T12:42:56Z")

</div>

hi there!  
I'm doing a chatbot for instagram, and I came across a situation. I made a script to put in an array each messages that the bot returns, but it returns with some messages with order exchanged/shuffled. So I applied a delay node. But I wanted to put an async function to improve performance.  
Would there be a node that does this function?

below the flow diagram

```auto
[{"id":"38728f55c6274ca7","type":"function","z":"a356a8194128f9f2","name":"main function// async..await","func":"//tipo da mensagem\nvar typemsg = msg.payload.type;\n\n//id da mensagem\nconst chatId = msg.payload.chatId;\n\n//opções criadas no nó anterior\nvar options = msg.payload.options;\n\n//id da sessão\nvar sessionId = msg.payload.session_id;\n\n//conteúdo da mensagem\nvar msgMsg = msg.payload.content;\n\n//tamanho do array da mensagem\nvar tamanho = msg.payload.content.length;\n\n//array que receberá as novas mensagens\nvar newMsg = await [];\nconsole.log(newMsg);\n//refatorar loop para aplicar função assincrona\n\nlet controleMsg = async () => {\nfor (const lines of msgMsg){\n if(lines.response_type == \"text\"){\n newMsg.push({\n payload:{\n type:typemsg,\n chatId:chatId,\n session_id: sessionId,\n content:lines.text,\n response_type: lines.response_type,\n \n }\n })}else{\n newMsg.push({\n payload:{\n type:typemsg,\n chatId:chatId,\n session_id: sessionId,\n content:lines.title,\n response_type: lines.response_type,\n options: options\n \n }\n })}\n}\nreturn [newMsg];\n}\n\n\n\n\n\n\n//retorna as mensagens para o novo array\n\n\n\n//futuramente será incerido função assincrona.\n//ver função for...of JavaScript","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":220,"y":740,"wires":[[]]}]

```

but to advance, the function that is checking is this:  
I tried to apply an async function and return the contents to the array, but it doesn't debug.

```auto
//type of msg
var typemsg = msg.payload.type;

//id of msg
const chatId = msg.payload.chatId;

//menu options
var options = msg.payload.options;

//id da sessão
var sessionId = msg.payload.session_id;

//content of mensagem
var msgMsg = msg.payload.content;

//array that will receive as new messages
var newMsg = await [];

let controleMsg = async () => {
for (const lines of msgMsg){
    if(lines.response_type == "text"){
         newMsg.push({
        payload:{
            type:typemsg,
            chatId:chatId,
            session_id: sessionId,
            content:lines.text,
            response_type: lines.response_type,
            
        }
    })}else{
         newMsg.push({
        payload:{
            type:typemsg,
            chatId:chatId,
            session_id: sessionId,
            content:lines.title,
            response_type: lines.response_type,
            options: options
            
        }
    })}
}

}

return [newMsg];

```

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [28 January 2022 12:54 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/2 "2022-01-28T12:54:19Z")

</div>

You cannot use return due to async nature.

Use node.send instead..

example...  
 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/c/8/c8fc0e8802425af91675567ccbf11031061b4c7b.png)

```auto

var data = [
    "1", "2", "3"
];

let asyncSender = async () => {
    const messages = [];
    data.forEach(e => {
        messages.push({ payload: e } )
    })
    node.send([messages]);
}
node.warn("before asyncSender")
asyncSender()
node.warn("after asyncSender")

```

---

<div class="post-metadata">

**Author:** ![TotallyInformation](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/totallyinformation/32/31_2.png) [@TotallyInformation](https://discourse.nodered.org/u/TotallyInformation)\
**Post date:** [28 January 2022 12:56 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/3 "2022-01-28T12:56:02Z")

</div>

I think you have the logic confused I'm afraid.

The controleMsg isn't going to be created until after you have returned. You need instead to have a node.send() inside the async.

Also, I don't think that `var newMsg = await [];` is doing anything with the await since `[]` is not a promise.

---

<div class="post-metadata">

**Author:** ![wjr1506](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/wjr1506/32/50619_2.png) [@wjr1506](https://discourse.nodered.org/u/wjr1506)\
**Post date:** [28 January 2022 14:31 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/4 "2022-01-28T14:31:08Z")

</div>

had put it to test if it had any impact, forgetting to take

---

<div class="post-metadata">

**Author:** ![wjr1506](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/wjr1506/32/50619_2.png) [@wjr1506](https://discourse.nodered.org/u/wjr1506)\
**Post date:** [28 January 2022 14:33 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/5 "2022-01-28T14:33:13Z")

</div>

it's a great approach, I really didn't know there was this method to return the function, however, in the console it prints the logs all in the sequence, however, when the bot sends the message, the messages are still disordered.

---

<div class="post-metadata">

**Author:** ![wjr1506](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/wjr1506/32/50619_2.png) [@wjr1506](https://discourse.nodered.org/u/wjr1506)\
**Post date:** [28 January 2022 14:35 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/6 "2022-01-28T14:35:03Z")

</div>

I applied await in node.send, but the same effect happens

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [28 January 2022 14:40 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/7 "2022-01-28T14:40:04Z")

</div>

> [@wjr1506](#):
>
> in the console it prints the logs all in the sequence, however, when the bot sends the message, the messages are still disordered

Can you explain - with perhaps a screenshot showing what you get, what you expected?

---

<div class="post-metadata">

**Author:** ![wjr1506](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/wjr1506/32/50619_2.png) [@wjr1506](https://discourse.nodered.org/u/wjr1506)\
**Post date:** [28 January 2022 14:54 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/8 "2022-01-28T14:54:26Z")

</div>

OK

 ![Captura de tela 2022-01-28 114657](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/9/b92fb17b54823e5f1073ab0c9a7188ba4470d6e3.png)

when you send a "hi" that would be a greeting, it answers these two messages, one for reply and another with options, in the console (left side) it prints the message correctly. But when sending to chat (right side), messages are sent randomly

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [28 January 2022 15:10 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/9 "2022-01-28T15:10:07Z")

</div>

Try adding a delay node(set to rate limit mode of 2 msg per 1 sec\*) immediately before the telegram node.

Does that solve the problem?

* * *

\*(2 msg per 1 sec will essentially space out message by 500ms)

Also, be sure to set the polling to \< 500ms in the bot config

---

<div class="post-metadata">

**Author:** ![wjr1506](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/wjr1506/32/50619_2.png) [@wjr1506](https://discourse.nodered.org/u/wjr1506)\
**Post date:** [28 January 2022 17:38 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/10 "2022-01-28T17:38:37Z")

</div>

very likely it will work.  
before trying to do it by async, I set some delays that checked what messages were going through and delayed sending. but I found a plastered method.  
I will try to delay the flow of messages through node, thanks!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [11 February 2022 17:38 UTC](https://discourse.nodered.org/t/async-function-for-sending-messages-chatbot/57403/11 "2022-02-11T17:38:42Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
