After creating the order, the client goes to the page where the bots respond to him at random intervals (to fulfill his order). Bots push in the socket via php, nodejs accepts and renders on the page.

Bots must periodically push messages to the chat, do it asynchronously, because bots from the server can come in a random time interval.

Code on nodejs

managementNsp.on('connection', function(socket){ socket.on('addBid', function (data) { if (data.writer.isBot) { function asyncPushToChat() { var messagesArray = ["Hello", "Test message"]; messagesArray.forEach(function(item) { setTimeout(function(){ push(item); }, randomSeconds); }); } } }); 

How to make asyncPushToChat function asynchronous ??

if so rewritten for promises, is that correct?

 managementNsp.on('connection', function(socket){ socket.on('addBid', function (data) { if (data.writer.isBot) { function asyncPushMessageToChat() { return new Promise(function(resolve, reject) { connection.query("SELECT text FROM bot_message", function (err, messagesArray) { if (err) { reject(err); } messagesArray.forEach(function(item) { setTimeout(function(){ return resolve(item); }, randomSeconds); }); }); }); } asyncPushMessageToChat() .then(function(res) { //append to html }) .catch(function(err){ console.log(err); }); } }); 
  • asyncPushToChat is already asynchronous, due to the use of setTimeout, it was simply not anywhere - Grundy
  • one
    if so rewritten for promises, is that correct? - not. because for one Promise there is an attempt to execute the function function several times - Grundy
  • one
    instead of forEach in promis - an array of promises, then Promise.all - n3r0bi0m4n

1 answer 1

Rewrote so

 if (data.writer.isBot == 1) { connection.query("SELECT text FROM bot_message WHERE bot_id = ?", data.writer.id, function (err, rows) { if (err) reject(err); for (var i in rows) { var messageData = { from : data.writer.id, orderId : data.bidding.orderId, isPing : data.order.isPing, to : data.bidding.userId, bidding : data.bidding.id, message : rows[i].text }; (function(i, messageData) { setTimeout(function () { clientSocket.emit('emulateSendMessage', messageData); }, 6000 * i); })(i, messageData); } }); }