Avoiding the deferred anti-pattern [duplicate]

2019-02-17 21:58发布

问题:

This question already has an answer here:

  • What is the explicit promise construction antipattern and how do I avoid it? 2 answers

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?

回答1:

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.