gubera
gubera

Reputation: 102

foreach loop with regular timeout in nodejs

I am trying to send the values from server to the client-side. Here, I have lot of values in my database so what I need is after fetching all the values I want to loop it send each value to client with regular pause after each value.. I have tried setTimeout() but still i cant get desired result...

server.js :

var express = require("express");
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

connection.query("select * from base_table", function (err, rows) {
    if (err) {  err; } else {
       rows.forEach(function(index){
          setTimeout(function(){
              io.emit('Fetched Values', index);
          }, 1000);
       }); 
    }
});

Client.js:

socket.on('Fetched Values', function(data) {
    console.log(data);
});

Upvotes: 0

Views: 1631

Answers (2)

Jake Holzinger
Jake Holzinger

Reputation: 6063

The array.forEach() method is synchronous so it is not ideal for asynchronous looping. You can create your own method for looping asynchronously, or use a module like async which has a lot of nice features to support a variety of use cases rather than just looping. Promises are also very powerful for performing asynchronous tasks, but there is a bit of learning overhead to use them properly.

Here's a simple method that can perform a for each loop asynchronously.

function asyncForEach(array, timeout, callback, index) {
    index = index || 0;
    setTimeout(function() {
        callback(array[index], index);
        if (array.length > index + 1) {
            asyncForEach(array, timeout, callback, index + 1);
        }
    }, timeout);
}

asyncForEach([1, 2, 3], 1000, function(number, index) {
    console.log(number + ' ' + index);
});

Upvotes: 0

elvis_ferns
elvis_ferns

Reputation: 524

connection.query("select * from base_table", function (err, rows) {
  if (err) {  err; } else {
   let promise = Promise.resolve();
   rows.forEach(function(index){
      promise = promise
       .then(() => {
          return new Promise((resolve) => {
            setTimeout(function(){
             resolve(io.emit('Fetched Values', index));
            }, 1000); 
          })
       })

    }); 
  }
});

Upvotes: 1

Related Questions