A function call returns 'undefined'

I have a form on my page. When the user clicks the "Send" button, in the background he also generates a unique_number, calling the function that generates this number, and also checks in the database that this number does not exist; if so - generates it again, if not returns - returns this number. However, for some reason, when I try to print this number on a page or warn about it, I get undefined , although the function returns the number. Here's the function call:

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

And here is 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 get results if it is true - it generates a new number, if false - should be returned. I tried alert num on the else part, and he issued a warning, but the answer is undefined. Why is this happening and how to fix it?

0
source share
1 answer

For a solution using deferred objects, try the following:

 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, of course, has not been verified, since I do not have your API, but the theory is that if result is true , calling .then returns the result of a recursive call to the same function. If result is false , then it returns the selected number as the (permitted) result of the new promise.

If any AJAX call fails, the loop should break, and you can catch it when calling .fail :

 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 a recursive call is not truly recursive - since AJAX is event driven, the original function has already completed and cleared its stack long before the AJAX .then event occurs. 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 a lot easier to get the server by a random number.

+1
source

Source: https://habr.com/ru/post/1486025/


All Articles