Calling for a function returns 'undefined' [duplicate]

你说的曾经没有我的故事 提交于 2019-12-13 21:08:47

问题


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 checks in the DB that this number doesn't exist; if it does - generates it again, if doesn't - returns this number. However, for some reason when I'm trying to print out this number to the page, or alert it - I'm getting undefined, though the function returns the number. Here's the call for the function:

var unique_num = create_unique_number();
alert(unique_num);
    rest of this function...

And here's the function itself:

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

$.getJSON("inc/API.php", 
{
    command:"is_unique_number_exist",
    unique_num:num
},
    function(result){
        if(result==true){
            create_unique_number();
        }
        else
        {
            return num;
        }
    });
}

I do get the results, if it's true - it generates new number, if false - should return. I tried to alert the num in the else part, and it did Alert the number, but on return - undefined. Why is it happening and how to fix it?


回答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.



来源:https://stackoverflow.com/questions/17083011/calling-for-a-function-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!