Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding the deferred anti-pattern [duplicate]

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?

like image 275
Ben Aston Avatar asked Feb 27 '15 11:02

Ben Aston


1 Answers

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.

like image 104
dfsq Avatar answered Oct 12 '22 23:10

dfsq