how to force execution of requests inside async.each with nodejs?

126 views Asked by At

I have a async.each that iterates an array and for every element inside the array it execute a function "check" that has a request inside. This is the code but when I run it I see from the debugger that node doesn't execute the check function and it block its execution.

async.each(array,
  function(v_page, callback){
    if(v_page.url.length>=5){
      internals.check(v_page.url,array2, function (body) {
        callback();
      });
    }
  },
  function(err){
    internals.calls(var1,var2,var3);
});

I tried with a normal for loop but it jump at the internals.calls function without execute the internals.check function for the async nature of node. So how can i force the execution of the check function?

This is the code of the check function:

internals.check = (url,array2,cb) => {
  request(url, function(err, recordset) {
    if(err){
      cb(array2);
    }else {
      //some stuffs
      cb(array2)
    }
  });
};
1

There are 1 answers

6
alexmac On

You call callback only when v_page.url.length >= 5, but you need to do that for each element:

async.each(array, function(v_page, callback) {
 if(v_page.url.length >= 5) {
   internals.check(v_page.url,array2, function(body) {
     callback();
   });
 } else {
   callback(); <== call callback here, when condition is not met
 }
 ...

Another problem is that, you incorrectly call callback in internals.check. According Node.js notation, the first parameter of callback must be an error or null (async uses this notation). But in your case you call callback with array2 anyway:

internals.check = (url, array2, cb) => {
  request(url, function(err, recordset) {
    if (err) {
      cb(err); // <== pass error here
    } else {
      cb(null, array2); // <== no error, so first parameter is null, the second is data
    }
  });
};