0

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);
});
1
  • You can use a promise chain that sets the next timeout after the previous one is invoked Commented Feb 23, 2018 at 5:34

2 Answers 2

1
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); 
          })
       })

    }); 
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah this works ! Being newbie , I never have used Promise function in nodejs... I will look deep into this ! Thanks ... It saved my time
0

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);
});

1 Comment

It was originally designed for use in node, but it works in the browser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.