A
A
Alex Wells2015-11-12 15:10:53
Node.js
Alex Wells, 2015-11-12 15:10:53

Asynchronous loop without waiting for element to finish processing?

Hello. There is an array. For each element of the array, you need to asynchronously, without waiting for the end of processing, to call event. For this, I decided to use AsyncEventEmitter, here's what happened, using an example:

for(var i=0; i<20; i++) {
  events.emit('test', '...');
}
events.on('test', function(data) {
  console.log('START');
  var sl = sleep(random.integer(1000, 5000));
  sleep(sl);
  console.log('END AFTER ' + sl);
});

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds) break;
  }
}

Unfortunately, this does not work, the next event is called only after the end of the previous one. This doesn't suit me at all. And even if you remove the events, and replace the usual for loop with an async library, it's still nothing. For the life of me, I don’t understand how to make it call all the events at once. sleep() is used purely to simulate long processing, it is a loop.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yeti357, 2015-11-12
@Alex_Wells

Either you don't understand how nodejs works, or you don't formulate your question accurately.
Regarding what you wrote:

for(var i=0; i<20; i++) {
  events.emit('test', '...'); // при первой итерации емитится событие
}
events.on('test', function(data) {
  console.log('START');
  // если бы здесь был асинхронный вызов(обращение к бд/запрос на удалённый сервер и тд), 
  // то проблем бы не было  
  var sl = sleep(random.integer(1000, 5000)); // разобрана ниже
  sleep(sl);
  console.log('END AFTER ' + sl);
});

function sleep(milliseconds) { // функция вызываемая внутри события,
// она выполняется в основном потоке(для nodejs он один!), и соответсвенно блокирует(!) 
// поток выполнения, поэтому у вас не срабатываю остальные вызовы функции.
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds) break;
  }
}

By comment
It can ONLY be synchronous
it cannot be.
But in general, look also at setImmidiate

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question