Kivylius
Kivylius

Reputation: 6547

Execute recursive function and save the callback

I have the following code. It runs a simple function and the same function needs to run. (Recursive)

var Skit = function(callback) {
    validSkit(Math.random(),function(skit,data){
        // Ajax callback
        if (skit == true) callback(data); // Works if skit is found
        else if (skit == false) Skit(callback); // Call Skit again [not working]
    });
}(function(skit){
    console.log("Valid skit found!");
});

I'm getting Skit is undefined! I know I could do this true simple function Skit().. call. But this is not my requirements. Is this possible?

Upvotes: 1

Views: 65

Answers (2)

Anton Savchenko
Anton Savchenko

Reputation: 1220

In this case var Skit variable is the returned value.

(function (callback) {
...
})(function () {console.log('I am argument function')}); 

If you returned smth from it (after validSkit execution, for exampe, or before, whatever) then the value of Skit would be return value. As far as return statement is absent, it returns undefined by default.

So you need firstly to initiate function without calling it and then call it by its name:

 var Skit = function(callback) {
    validSkit(Math.random(),function(skit,data){
        // Ajax callback
        if (skit == true) callback(data); // Works if skit is found
        else if (skit == false) Skit(callback); // Call Skit again [not working]
    });
};

Skit(function(skit){
    console.log("Valid skit found!");
});

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382132

You should use a named function expression here:

(function Skit(callback) {
    validSkit(Math.random(),function(skit,data){
        // Ajax callback
        if (skit == true) callback(data); // Works if skit is found
        else if (skit == false) Skit(callback); // Call Skit again [not working]
    });
})(function(skit){
    console.log("Valid skit found!");
});

Note that the Skit name won't leak in the outside scope and it will be available for debug in the stack traces.

Upvotes: 2

Related Questions