Given these functions:
function func1() {
var dfd = $.Deferred();
setTimeout(function() {
dfd.resolve('Password');
}, 1000);
return dfd.promise();
}
function func2(message) {
var dfd = $.Deferred();
setTimeout(function() {
if (message == 'Password') {
dfd.resolve('Hello World');
}
}, 1000);
return dfd.promise();
}
I'd like to find a better way to do the following. Note this is using jQuery 1.8.x.
var promise = func1();
promise.done(function(message1) {
var promise2 = func2(message1);
promise2.done(function(message2) {
alert(message2);
});
});
Any ideas? I thought using jQuery #pipe or #then would work but I can't figure it out. Here is a fiddle to play around: http://jsfiddle.net/Z7prn/
Use JQuery.when(). It is exactly what you want to chain an array of deferreds and run a function when all are done.
Update 2017 (after seeing downvotes):
What OP wanted was a better version of his code to run promises sequentially. Here is my version using
$.when
:I had a similar use case, so I think this should help you out.
The following method will take an array of methods (which may or may not return Promises) and execute them in sequence, waiting until each deferred is complete before proceeding. Default behavior is to stop on failure; second argument lets you proceed whether the call fails or not.
done/fail handler signatures are (Array<context>) Function (Array<Object{ rejected|resolved: arguments }>), where context is the context of each resolveWith/rejectWith call, or the deferred in question, and arguments is the argument set that was passed in the resolution / rejection.
A simple example of use: http://jsfiddle.net/rG9rA/
It's not that complicated (either use
.then
or.pipe
, they are both the same since jQuery 1.8 I think).Since
func2
returns a new deferred object, the.done
callback is attached to that one instead.DEMO