You have a couple problems:
- You were never resolving your deferred. You have to call
def.resolve()
for it to notify the promise listeners that the promise is now resolved.
function1().done(function2());
needs to be function1().done(function2);
. When you have the parens after function2()
that tells the JS interpreter to call the function immediately and pass the return value which is undefined
. Without the parens passes a reference to the function as a .done()
handler so the promise infrastructure can call it later (that's what you want).
I'd suggest the following code:
function function1() {
return $.Deferred(function(def) {
console.log("start of function1");
setTimeout(function() {
console.log("timer fired");
def.resolve();
}, 3000);
}).promise();
}
function function2() {
console.log('done');
}
$("button").click(function() {
function1().then(function2);
});
In addition to fixing the above issues, this also changes:
- It uses the deferred constructor. This saves some code (uses fewer intermediaries) and is more compatible with the ES6 promise specification and supported by jQuery.
- It uses
.then()
instead of the jQuery-proprietary .done()
which is more compatible with the ES6 promise specification and supported by jQuery.
I'd also suggest that you upgrade to a newer release of jQuery as 1.10 is already 3+ years old by now. If you absolutely have to maintain compatibility with older versions of IE, you can at least use 1.12.4.