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) {
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.
source share