0

How do I iterate over a asynchronous function in nodejs stopping depending on callback return?

Example:

suppose I have following function

var fn1 = function(i, callback){
    // code here
    callfunction(i, function(err, p2){
         if(err) throw err;
         if(something) return callback(true);
         else return callback(false);
    });
}

I need to iterate and call for i=1,2,3,... until my callback returns false.

I tried using async whilst, but I do not think it can helps me, because the test function also needs callback, and the function for test and iteratee are same, I cannot call twice.

Chandan Rai
  • 9,879
  • 2
  • 20
  • 28
Rogger Fernandes
  • 805
  • 4
  • 14
  • 28

1 Answers1

0

If I understand your problem correctly. What about some recursion

const maxTries = 10;

// just a stupid counter to run a be able to change return value
let numberOfCalls = 0;

const asyncCall = () => {
  if (numberOfCalls === 9) {
    return Promise.resolve(false);
  }
  numberOfCalls += 1;
  return Promise.resolve();
};

function iterate(calls = 0) {
  if (maxTries === calls) {
    return Promise.resolve();
  }
  return asyncCall().then(value => {
    if (value === false) {
      return value;
    }
    return iterate(calls + 1);
  });
}

iterate().then(result => {
  if (result === undefined) {
    //to many tries
  }
  console.log('result', result);
});
pethel
  • 5,397
  • 12
  • 55
  • 86