jQuery $.when() where one of its parameters comes via an asynchronous “Deferred pipe”
http://stackoverflow.com/questions/12282309/jquery-when-where-one-of-its-parameters-comes-via-an-asynchronous-deferred
JavaScript
function foo() {
var time = Math.floor(Math.random() * 3000),
d = $.Deferred();
console.log('foo starting: ' + time);
setTimeout(function() {
console.log('foo resolving');
d.resolve(time);
}, time);
return d.promise();
}
function bar() {
var time = Math.floor(Math.random() * 500),
d = $.Deferred();
console.log('bar starting: ' + time);
setTimeout(function() {
console.log('bar resolving');
d.resolve(time);
}, time);
return d.promise();
}
function baz(previousTime) {
var time = Math.floor(Math.random() * 500),
d = $.Deferred();
console.log('baz starting: ' + time);
setTimeout(function() {
console.log('baz resolving');
d.resolve(previousTime + ' + ' + time + ' = ' + (previousTime + time));
}, time);
return d.promise();
}
$.when(foo(), bar().pipe(baz))
.then(function(foo, barBaz) {
console.log('when OK', [foo, barBaz]);
});