Skip to content Skip to sidebar Skip to footer

Node.js Synchronous Loop

I'm new to node.js and I'm wondering if it is possible to iterate in a loop synchronously. Let's say that in a for loop I call a blocking function (reading, writing) and I want tha

Solution 1:

You shouldn't use a for loop for this. The for loop will fire off each of the async functions simultaneously which is obviously not what you want. You should create your own system for calling these. Try something like this:

  1. You'll want an array to hold all of the URL's that you want to hit
  2. You'll want to create a function that calls the first URL in the list and waits for the response
  3. In the callback function to this call, once all of the asynchronous work is done, call the same function to restart process until it is out of URL's to hit

Should look a little like this:

var urls = newArray("google.com", "youtube.com", "stackoverflow.com");

functioncallFirstInArray() {
   var url = urls.shift(); //removes the first from the array, and stores in variable 'url'//do ajax work, and set callback function:
   $.ajax(/*do stuff with the url variable*/, function () { 
      if (urls.length > 0) {   //callbackcallFirstInArray();
      };
   });
};

Yours may not work exactly how I described it here, but it should use a similar concept to it.

Note: You will probably need an extra function scope to protect your original array of URL's because .shift() will mutate the original array

Solution 2:

You mention that you are reading and writing files, are you using fs.readFile and fs.writeFile? These are asynchronous methods, and you would need to invoke one after the other in callbacks.

If you do want to use a loop, take a look at the synchronous versions of those methods fs.readFileSync and fs.writeFileSync.

Post a Comment for "Node.js Synchronous Loop"