Skip to content Skip to sidebar Skip to footer

Calling For A Function Returns 'undefined'

I have a form on my page. When the user hits the Send button, in the background it also generates a unique_number by calling for a function that generates this number and also chec

Solution 1:

For a solution using deferred objects, try this:

function create_unique_number()
{
    var num = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000;

    return $.getJSON("inc/API.php", {
        command:"is_unique_number_exist",
        unique_num:num
    }).then(function(result) {
        return result ? create_unique_number() : num;
    });
}

This is of course untested as I don't have your API available, but the theory is that if result is true the .then call returns the result of a recursive call back to the same function. If result is false then it returns the chosen number as the (resolved) result of a new promise.

If any AJAX call fails, the loop should break and you can trap that with a .fail call:

create_unique_number().done(function(n) {
    // use your unique number "n" here
    var unique_num = n;
    ...
}).fail(function() {
    // there was an AJAX error
});

// can't use "unique_num" here - execution continues here immediately
// and "unique_num" isn't defined until the above ".done" callback is
// invoked some time later

Note that the recursive call isn't truly recursive - since AJAX is event driven, the original function will already have terminated and cleaned up its stack long before the AJAX .then event fires. The resulting new call to create_unique_number will be at the same "call stack" level as the original call.

Also, as pointed out in the comments, it would actually be far simpler to have the server give you a random number.


Post a Comment for "Calling For A Function Returns 'undefined'"