3

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 Answer 1

4

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
    }
  });
};
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, I added it but nothing changed and above all I did not solve the problem... It doesn't execute the check function.
Updated the answer, you have a bug in internals.check function.
ok I fix the callback bug but from the debugger i saw that it enters inside the check function and when it arrives to request, it jump to the end of the function so it doesn't see the callback cb. I think that this is the problem.
Of course it jumps to the end, because request is `asynchronous_ function, it returns immediately and later, when data is loaded, calls callback.
so there isn't any solution?
|

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.