Skip to content

Commit 848491c

Browse files
committed
avoiding for loop
1 parent 6e23b6a commit 848491c

File tree

1 file changed

+17
-20
lines changed

1 file changed

+17
-20
lines changed

niceday-broker/index.js

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ require('dotenv').config();
1414
const { THERAPIST_PASSWORD, THERAPIST_EMAIL_ADDRESS, ENVIRONMENT } = process.env;
1515
let { RASA_AGENT_URL } = process.env;
1616
RASA_AGENT_URL = (RASA_AGENT_URL === undefined) ? 'http://rasa_server:5005/webhooks/rest/webhook' : RASA_AGENT_URL;
17-
// proportional factor between the number of words in a message and the time to wait before the
18-
// newt message is delivered
19-
WORDS_PER_SECOND = 5
17+
// proportional factor between the number of words in a message and the time to wait before the
18+
// newt message is delivered
19+
const WORDS_PER_SECOND = 5;
2020
// maximum delay between a message and the next one
21-
MAX_DELAY = 10
21+
const MAX_DELAY = 10;
2222

2323
const chatSdk = new Chat();
2424
let selectedServer;
@@ -80,28 +80,25 @@ function sleep(ms) {
8080
async function onRasaResponse() {
8181
if (this.readyState === 4 && this.status === 200) {
8282
const responseJson = JSON.parse(this.responseText);
83-
for (message of responseJson){
84-
const attachment = {
83+
84+
const processMessage = async (message) => {
85+
const attachment = {
8586
replyOfId: null,
86-
attachmentIds: [],
87+
attachmentIds: message.metadata || [],
8788
};
88-
if ('metadata' in message) {
89-
attachment.attachmentIds = message.metadata;
90-
}
91-
92-
sendMessage(message.text, parseInt(message.recipient_id, 10), attachment)
9389

94-
if (ENVIRONMENT === 'prod') {
95-
const delay = (message.text.split(" ").length)/WORDS_PER_SECOND;
96-
97-
if (delay > MAX_DELAY) {
98-
delay = MAX_DELAY;
99-
}
90+
sendMessage(message.text, parseInt(message.recipient_id, 10), attachment);
10091

101-
await sleep(delay*1000);
92+
if (ENVIRONMENT === 'prod') {
93+
const delay = Math.min(MAX_DELAY, message.text.split(' ').length / WORDS_PER_SECOND);
94+
await sleep(delay * 1000);
10295
}
103-
}
96+
};
10497

98+
await responseJson.reduce(async (prevPromise, message) => {
99+
await prevPromise;
100+
await processMessage(message);
101+
}, Promise.resolve());
105102
} else if (this.readyState === 4) {
106103
console.log('Something went wrong, status:', this.status, this.responseText);
107104
}

0 commit comments

Comments
 (0)