Answer the question
In order to leave comments, you need to log in
How to delay code execution until a response is received from the server?
I am writing a telegram bot on Nodejs. The bot is receiving messages. It received a message of type start, then it received data, then it received a message of type end. When it receives data between start and end, you need to send the data to the server and get a response, and when you press end, you need to use this data. The problem is that the user can send end too quickly and then the data will not have time to be processed. Here is a code snippet (there are many such if / else. I understand that you need to use promises or await / async, but I can’t understand how this is done in such a construction
bot.on('message', msg => {
if (msg.text == "start") {
....
} else if (msg.text == "send" ) {
bot.getFileLink(file.file_id).then(url => {
cloudinary.uploader.upload(url, function(res) {
files.push(res.url);//1
})
})
} else if (msg.text == "end") {
console.log(‘files = ', files);//2
}
})
Answer the question
In order to leave comments, you need to log in
It is necessary to keep the state of the dialog, individual for each user.
Put user commands in a queue, and somehow mark “where we are now”: we are waiting for the next command from the user or we are waiting for a response from the server.
The state can be kept in Redis, MySQL, or another database. The incoming message from the user contains it from.id
- the dialog is identified by it and its state is taken.
Promises and other async will not help here, since the matter is wider than one request.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question