M
M
magogo2019-03-08 07:32:56
JavaScript
magogo, 2019-03-08 07:32:56

Correspondence on AJAX Long-polling. Will you help?

I am creating personal correspondence using AJAX long-polling, I ran into a problem: I need to send a response from the server to the client (see code)

var arr = [];

app.post('/post', function (req, res) { //  На этот адрес приходят сообщения
  var message = req.body; //  Получаем сообщение
  arr.push(message); //  Добавляем его в массив
});


app.get('/im:id', function (req, res) { //  Клиент запрашивает ответ AJAX'ом
  req.params.id = req.query.uid_from;
  onSubscribe(req, res); //  Ждет ответа от этой функции

  function onSubscribe(req, res) {
    var answer = arr.find(i => i.uid_from == 1); //  Ищет ответ по параметру uid_from == 1 (просто для примера)
    if (answer !== undefined) { //  Если ответ по заданному параметру есть
      res.send(answer); //  Отправляем ответ
    }
    arr = []; //  Очищаем массив (надо доработать)
  }
  return;
});

An example of data in an array:
[  
   { msg: 'dsfsdfsdfsdf', uid_from: '5', uid_to: '2' },
   { msg: 'dsfsdfsdfsdf', uid_from: '1', uid_to: '9' },
   { msg: 'dsfsdfsdfsdf', uid_from: '9', uid_to: '1' },
   { msg: 'dsfsdfsdfsdf', uid_from: '2', uid_to: '5' }
]

The problem is that the onSubscribe function only loops through the array once when it's called. Somehow it is possible to constantly "monitor" this for changes in the array? What would then send the answer?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey, 2019-03-08
@VladimirAndreev

setInterval on the answer search function

C
Chris, 2019-03-08
@tv_dakota

Of course, sorry, long polling on the node? Seriously? Why not sockets?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question