Egidi
Egidi

Reputation: 1776

Javascript calling function from inside same function

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 
  })

Upvotes: 1

Views: 21883

Answers (2)

YuraA
YuraA

Reputation: 67

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.

Upvotes: 0

dfsq
dfsq

Reputation: 193261

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);
}

Upvotes: 6

Related Questions