Last Updated: February 25, 2016
·
472
· aali

Node Loops

If you are coding in Node, and if you are like a total beginner or do not want to use any module, you'll definitely face with a problem like;

"I have jobs to be done inside a loop that takes longer time than the iteration itself"

My response; Of course! Say you are using Redis and even with a simple like going to Redis and fetching some multiple values and later on processing them according to a logic will take much more than the simple iteration. We are comparing "getListOfAllUsers" to "i++" people.

So here is a trick I would suggest. Loop counters! Here is something that would cause a problem;

for(var i=0;i<someList.length;i++) {
    fetchInformation(someList[i]);
}

console.log("Success");

Result? Of course, FAIL. However here is how to turn things around;

  1. Insert a callback parameter that will take a function that will be triggered once the operation is done.
  2. Insert a loopCounter that will actually decide when to end your loop.

So the new code would be like;

var loopCounter = 0;
for(var i=0;i<someList.length;i++) {
    fetchInformation(someList[i], function(data) {
        loopCounter++;
    });
    if(loopCounter == someList.length) //Think it like loop.on("finished") event
        console.log("Success");
}

Hope you enjoy or would show me a better way to implement this. But this is the way I use and hope it helps to some people struggling with Node's async structure.