19

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/

camwest
  • 333
  • 1
  • 3
  • 6

2 Answers2

39

It's not that complicated (either use .then or .pipe, they are both the same since jQuery 1.8 I think).

func1().then(func2).done(function(message) {
    alert(message);
});

Since func2 returns a new deferred object, the .done callback is attached to that one instead.

DEMO

Aidin
  • 25,146
  • 8
  • 76
  • 67
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    i love when people explain things in such concise manner. easier to understand and follow – tim Jul 15 '13 at 21:34
  • 3
    Note: Use `.then` since `.pipe` has been deprecated in jQuery 1.8 ([docs](http://api.jquery.com/deferred.pipe/)) – nhylated Nov 06 '14 at 04:17
6

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.

(function ($) {
    "use strict";
    var copy = function (a) {
        return Array.prototype.slice.call(a);
    };

    /**
        Handle a sequence of methods, stopping on failure by default
        @param Array<Function> chain    List of methods to execute.  Non-deferred return values will be treated as successful deferreds.
        @param Boolean  continueOnFailure   Continue executing even if one of the returned deferreds fails.
        @returns Deferred
     */
    $.sequence = function (chain, continueOnFailure) {
        var handleStep, handleResult,
            steps = copy(chain),
            def = new $.Deferred(),
            defs = [],
            results = [];
        handleStep = function () {
            if (!steps.length) {
                def.resolveWith(defs, [ results ]);
                return;
            }
            var step = steps.shift(),
                result = step();
            handleResult(
                $.when(result).always(function () {
                    defs.push(this);
                }).done(function () {
                    results.push({ resolved: copy(arguments) });
                }).fail(function () {
                    results.push({ rejected: copy(arguments) });
                })
            );
        };
        handleResult = continueOnFailure ?
                function (result) {
                    result.always(function () {
                        handleStep();
                    });
                } :
                function (result) {
                    result.done(handleStep)
                        .fail(function () {
                            def.rejectWith(defs, [ results ]);
                        });
                };
        handleStep();
        return def.promise();
    };
}(this.jQuery));

A simple example of use: http://jsfiddle.net/rG9rA/

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();
}

    $.sequence([func1, func2, function () { alert('done'); }]);
Fordi
  • 2,798
  • 25
  • 20
  • Nice. I added an optional "delay" between calls, in case some external code needs events to settle (I use Knockout) – Johnny O Aug 19 '17 at 20:13