How do you expect them to be executed in order if there is no dependency between them? $.when
doesn't have and cannot have an influence on the evaluation of the promise, it just waits until each of the promises is resolved.
Your code is way more complicated then it needs to be. $.ajax
already returns a promise which gets resolved when the Ajax response was received, so you can just return it from the functions. If you want to execute them in sequence, you can chain them via .then
:
These filter functions can return a new value to be passed along to the promise's
.done()
or.fail()
callbacks, or they can return another observable object (Deferred, Promise, etc) which will pass its resolved / rejected status and values to the promise's callbacks.
So your code simplifies to:
function aaa() {
w("begin aaa");
return $.ajax({
type: "GET",
data: {
m: 5
}
}).done(w);
}
function bbb() {
w("begin bbb");
return $.ajax({
type: "GET",
data: {
m: 1
}
}).done(w);
}
aaa().then(bbb).done(function() { w('ok'); });
Here, aaa().then(bbb)
creates the dependency you need. It basically means "once aaa
's promise is resolved, execute bbb
". In addition, .then
returns a new promise, which gets resolved when the promise returned by bbb
gets resolved, which allows you to execute a function when the promises of both, aaa
and bbb
are resolved.
Maybe these help you to understand promises (and deferreds) better:
Example without $.ajax
:
function aaa() {
var def = new $.Deferred();
setTimeout(function() {
def.resolve(21);
}, 3000);
return def.promise();
}
function bbb(v) {
var def = new $.Deferred();
setTimeout(function() {
def.resolve(v * 2);
}, 1000);
return def.promise();
}
// aaa -> bbb -> console.log
// The value is logged after 3 + 1 seconds
aaa().then(bbb).done(function(v) { console.log(v); }); // 42
// (aaa | bbb) -> console.log
// The value is logged after max(3, 1) seconds and both resolved values are
// passed to the final promise
$.when(aaa(), bbb(5)).done(function(v) { console.log(v); }); // [21, 10]