Reputation: 3
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:
<script>
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);
});
}
</script>
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.
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
.then( myFunc, myFailure );
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.
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.
Any help is really appreciated, thx!
Upvotes: 0
Views: 85
Reputation: 338128
You must always return something from an async function.
function GetNumbersFromServer() {
// here
return $.ajax({
url: getWebServiceUrl() + "GetNumbersFromServer",
type: "POST",
dataType: "xml",
cache: false,
data: {}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("GetNumbersFromServer: " + textStatus + " - " + errorThrown);
});
}
function CreateNumberList() {
// here, too
return GetNumbersFromServer().then(function(result) {
// do something with result
// and here
return data;
});
}
Note that there is no $.when()
necessary, the return value of GetNumbersFromServer()
is a fully functional promise.
With an unbroken chain of returns you can create an unbroken chain of worker functions:
CreateNumberList().then(function (data) {
// do something with data
return newData;
}).then(function (newData) {
// do something with newData
// and so on
});
Upvotes: 1