6

I have some code that looks like this:

function foo() {

    var deferred;

    deferred = q.defer();

    doSomethingAsync()
        .then(function(result) {
            var resultTransformed = doSomethingSynchronousToTheResult(result);
            deferred.resolve(resultTransformed);
        });

    return deferred.promise;

};

Maybe:

function foo() {            
    return doSomethingAsync()
        .then(function(result) {
            return doSomethingSynchronousToTheResult(result);
        });       
};

Would the above ensure that the transformed result is used further down the promise chain?

How can I refactor this to avoid the deferred anti-pattern?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    I would think this question is already handled in the canonical post, isn't it? `return doSomethingAsync().then(doSomethingSynchronousToTheResult)` is just the solution suggested there. – Bergi Feb 27 '15 at 12:05

1 Answers1

6

Deferred anti-pattern happens when new redundant deferred object is created to be resolved from inside an promise chain.

In your case you already have a Promise object, so you just need to return doSomethingAsync() result:

function foo() {
    return doSomethingAsync().then(function (result) {
        return doSomethingToTheResult(result);
    });
};

Would the above ensure that the transformed result is used further down the promise chain?

Yes, exactly, this is one of the coolest things about promises.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • But if the `doSomethingToTheResult` is asynchronous and not promise based, I *do* need to create a new deferred. Is that correct? – Ben Aston Feb 27 '15 at 15:27
  • 1
    If `doSomethingToTheResult` is async then yes, inside you would need to create deferred and return promise. – dfsq Feb 27 '15 at 16:20
  • @BenAston Either that, or you can create a promise using the promise constructor. – JLRishe Mar 20 '15 at 15:57