2

I've been doing some reading about queueing JS callbacks without stacking them over here, How do I animate in jQuery without stacking callbacks?

I've tried playing around Julian Aubourg's answer, and I noticed that after removing the "return" statements from the functions, everything happens at once.

I'm just wondering what the behavior of these return statements are, and what role they play in making this code synchronous.

    $('div1').fadeOut('slow').promise().pipe(function() {
        return $('div2').fadeOut('slow');
    }).pipe(function() {
        return $('div3').animate({ top: 500 }, 1000 );
    });
Community
  • 1
  • 1
Vincent Chan
  • 484
  • 1
  • 4
  • 12
  • 3
    FYI, `.pipe()` is deprecated. But your question isn't so much about the JavaScript language, as it is about the specific API jQuery defined. – Blue Skies Dec 05 '13 at 17:11
  • @BlueSkies in fact - his question is more about promises in general but other than that agreed. – Benjamin Gruenbaum Dec 05 '13 at 17:14
  • And as a sidenote, `pipe()` is replaces by `then()` – adeneo Dec 05 '13 at 17:15
  • The important part from the [documentation](http://api.jquery.com/deferred.pipe/) is: *"These filter functions can return [...] another observable object (Deferred, Promise, etc) which will pass its resolved / rejected status and values to the piped promise's callbacks."* – Felix Kling Dec 05 '13 at 17:15
  • @BenjaminGruenbaum: There's no such thing as promises in general. There are implementations of a concept, which can vary. This one is about jQuery's implementation. Or did I misunderstand you? – Blue Skies Dec 05 '13 at 17:15
  • 1
    @BlueSkies this is what I mean by "[promises in general](http://wiki.commonjs.org/wiki/Promises/A)" , jQuery follows the specification and this question is about that specification - although like you suggested - it contains the deprecated `pipe` and not the specification `then`. – Benjamin Gruenbaum Dec 05 '13 at 17:23

1 Answers1

4

All jQuery animations now return their own promise, so basically you're returning a promise that is resolved when the animation completes when you do :

return $('div2').fadeOut('slow');

It would be equivalent to

var def = new $.Deferred();
$('div2').fadeOut('slow', function() {
    def.resolve();
});
return def.promise();
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Worth mentioning - when you return from a promise anything that is not a promise - it resolves immidiately with that value (like in your case where you didn't have an explicit return so it returned `undefined`. If you return a promise, it'll resolve when the returned promise resolves. – Benjamin Gruenbaum Dec 05 '13 at 17:12
  • 1
    @BenjaminGruenbaum - good point, that's of course why it works with the return statement, and not without it. – adeneo Dec 05 '13 at 17:22
  • Thanks! I can't seem to find any documentation on this. How did you know about this? – Vincent Chan Dec 07 '13 at 00:58