0

I have two objects, ObjectA and ObjectB. I want to save ObjectB only after ObjectA is done, but I want to return a promise which wraps the result of both of them.

Here's my first hack at it to show the functionality that I want. This function works fine it's just ugly and surely there's a better way.

Functions saveObjectA and saveObjectB both return $.post() promises.

saveAAndBSequentially: function () {
    var dfd = $.Deferred();
    saveObjectA().done(function () {
        saveObjectB().done(function () {
            dfd.resolve();
        }).fail(function () {
            dfd.reject(); 
        });
    }).fail(function () {
        dfd.reject(); 
    });

    return dfd.promise();
}

I'd just use $.when and add a done callback on saveObjectA to trigger saveObjectB, but the deferred for saveObjectB doesn't exist yet so I don't believe I can use $.when on it right away.

Ideas on how to solve this is a more elegant manner are greatly appreciated!

Adam Terlson
  • 12,610
  • 4
  • 42
  • 63

1 Answers1

1

.pipe() does exactly the task you have handcoded:

var saveAAndBSequentially = function () {
    return saveObjectA().pipe(function () {
        return saveObjectB();
    });
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375