1

I have a function that does several DDBB calls, so it is asynchronous.

I need to call the function and check a data value (winner) in the JSON object it returns. If it is true i need to call the function again until winner == false.

I can't use while because it is not asynchronous, how can i do this?

  someFunction(function(result) {
     // if result.winner == true repeat 
  })
3
  • 2
    Put the call to the function inside the success where the results are actually returned. Commented Dec 21, 2014 at 11:57
  • 1
    Could you include the whole code snippet ? I'm specifically referring to the function which gets the code from the database. Commented Dec 21, 2014 at 11:59
  • @fornal you mean calling the function from inside the same function? Commented Dec 21, 2014 at 12:09

2 Answers 2

6

You can call the same callback function again until condition is true:

someFunction(function repeat(result) {
    if (result.winner) {
        someFunction(repeat);
    }
});

Check the demo below.

someFunction(function repeat(result) {
    document.body.innerHTML += '<br>' + result.winner;
    if (result.winner) {
        someFunction(repeat);
    }
});

var results = [true, true, true, false];
function someFunction(callback) {
    setTimeout(function() {
        callback({winner: results.shift()});
    }, (Math.random() + 1) * 1000 | 0);
}

Sign up to request clarification or add additional context in comments.

Comments

0

Have you looked at async.js? It has several control flow async functions. You probably want to look into whilst, doWhilst, until, doUntil:

https://github.com/caolan/async#whilst

whilst(test, fn, callback)

Repeatedly call fn, while test returns true. Calls callback when stopped, or an error occurs.

Comments

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.