Your second alert is never called because the original deferred you assign to the variable dd is never resolved and thus its .done() handler is never called.
You create a deferred and assign it to dd here:
var dd = $.Deferred();
And, then you set up a .done() handler with this:
dd.done(function() { alert(" dd.done outside ajax")});
But, when your ajax function finishes, you assign a different promise to the variable dd with this line:
dd = t();
And, thus nothing ever resolves the original promise so its .done() handler is never called.
I'd suggest this design instead:
function t() {
var d = $.Deferred();
setTimeout(function(){
d.resolve();
}, 5000);
return d.promise();
}
function test() {
return $.ajax("/echo/json/").then(function() {
console.log("ajax call done");
return t();
}).then(function() {
console.log("after timer");
});
}
test().then(function() {
console.log("everything done");
});
Working demo: http://jsfiddle.net/jfriend00/atafc5hj/
This illustrates the following concepts which are useful to know:
- Using the promise already returned from
$.ajax() rather than creating your own.
- Chaining another activity to that promise.
- Returning another promise from the
.then() handler to make the sequence wait for that promise too.
- Returning the chained promise from the main function so you can see when everything is done.