Using jquery 1.12 I need to wait for the results of two AJAX calls before I go any further. When I used $.when
I don't understand why I don't get the same results when I pass the $.ajax
directly and when I return a $.ajax
from a function call.
This works. In the done
part func1
is an array, with func1[0]
being the data returned:
$.when($.ajax({
url: url1,
type: 'GET',
dataType: 'json',
xhrFields: {
withCredentials: true
},
headers: {
Accept: "application/json; charset=utf-8"
},
success: function (data){
debugger;
}
}), $.ajax(...)
).done(function(func1, func2) {
debugger;
})
This does not. In the done
part func1
is undefined
:
var myfunc = function() {
return $.ajax({
url: url1,
type: 'GET',
dataType: 'json',
xhrFields: {
withCredentials: true
},
headers: {
Accept: "application/json; charset=utf-8"
},
success: function (data) {
debugger;
}
});
}
$.when(myfunc(), $.ajax(...)).done(function(func1, func2) {
debugger;
})
In the second case I just wrapped the first ajax call into a function.
EDITED
Probleme Solved. I wrote
return
$.ajax({
url: url1,...
instead of
return $.ajax({
url: url1,...
In the first case, the parser interprets the instruction as two instructions : return undefined then $.ajax. The $.ajax instruction is never executed because we already exited the function.
If func1
is undefined, perhaps myfunc()
is not returning anything? Should you not pass myfunc
as a function name instead of a function call, e.g. $.when(myfunc, $.ajax())
...?