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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With