I don't think this has been discussed on the boards yet. I've been researching chaining with promises and I found that you can chain promises to a specific deferrer. This allows all the functions registered through the then statements to be invoked asynchronously from what I have read. But, this assumes those functions are written asynchronously. So for example if I had the following:
function asyncEvent() {
var dfd = jQuery.Deferred();
dfd.resolve( "start" );
return dfd.promise();
}
$.when( asyncEvent() ).then(
function( status ) {
console.log(status);
setTimeout(function(){console.log("1");},1000);
}
).then(function (status) {
setTimeout(function(){console.log("2");},1000);
});
Part of this was taken from jquery's documentation.
The console would output 1 and 2 in order 1 second after status was shown. This is instead of showing 1, 1 second after status and then 2, 1 second after 1. So this method does not work for chaining synchronous functions.
I understand that there are ways to change the returned promise from each then. But, my question is, can the promise be changed implicitly within the then statement or do you have to use code like the following (which is the only way I can think to do it)? If so, could you show me a simplified version of the code that does this because I don't think the code on this page actually does this.
Notice the created deferred variable d is left in the scope chain when the function within the then returns. I would like to avoid this if possible. And it would be nice not to have to create it in the first place.
function asyncEvent() {
var dfd = jQuery.Deferred();
dfd.resolve( "start" );
return dfd.promise();
}
$.when( asyncEvent() ).then(
function( status ) {
var d=$.Deferred();
console.log(status);
setTimeout(function(){console.log("1");d.resolve();},1000);
return d.promise();
}
).then(function (status) {
setTimeout(function(){console.log("2");},1000);
});
Part of this was taken from jquery's documentation. EDIT: I understand that setTimeout isn't actually handled synchronously, but from an output standpoint it might as well be.