jQuery - AJAX: Call a ajax function by another function and wait for the respons before continue
<p>I have two functions, the first is CreateNumberList() in which I call the function GetNumbersFromServer() and with the result I want to create a list to use in the page. The second is GetNumbersFromServer() with ajax() who calls a Webservice and returns the numbers.
See code below:</p>

<pre><code>&lt;script&gt;
  function CreateNumberList() {
     $.when(GetNumbersFromServer()).then(function(result) {

     //Do something with result

      });
  }

  function GetNumbersFromServer() {
     $.ajax({
       url: getWebServiceUrl() + "GetNumbersFromServer",
       type: "POST",
       dataType: "xml",
       cache: false,
       data: {}
     }).done(function (data, status) {

       return data;

     }).error(function (jqXHR, textStatus, errorThrown) {
       console.log("GetNumbersFromServer: " + textStatus + " - " + errorThrown);
     });
  }
&lt;/script&gt;
</code></pre>

<p>The problem is, that the CreateNumberList() function don't wait for the result from the ajax() function. I know ajax() is asynchronous and the calling function doesn't wait for ajax(). For this reason I found the $.when() .then() function. The example from the jQuery API calls the ajax() direct in the when() function.</p>

<pre><code>$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
.then( myFunc, myFailure );
</code></pre>

<p>But I want to call my function in the .when() function and then use the result from it in the .then() function and not the ajax() direct in the .when() function for maintenance, complexity and cohesion reasons.</p>

<p>I get stuck at this and can't find any solution. I searched for several hours with no luck. I'm also not sure if "return" is the correct way to return the value from the function and if I have to create a deferred object first to callback/return the result.</p>

<p>Any help is really appreciated, thx!</p>