2

In the following code, what would be the reason to return another promise from the success or err method? As you can see, someFunction already returns a promise and we could easily return that to the caller.

I don't understand the reason to make another promise while we are not decorating/manipulating the response or the error. Is there a use case that I'm not aware of?

function() {
    var p = $q.defer();

    someModule.someFunction(input)
    .then(
      function(success) {
        return p.resolve(success);
      },

      function(err) {
        return p.reject(err)
      }
    );

  return p.promise;
};
paytonpy
  • 291
  • 2
  • 7
  • There is no reason but inexperience, or just intentionally bad code. Even if you were to manipulate the response or error, you should not create a deferred. – Bergi Sep 19 '15 at 19:07

2 Answers2

3

This whole thing can be replaced with:

function someFunc() {
    return someModule.someFunction(input);
}

It is considered an anti-pattern to create your own promise which you then resolve and reject when you could just use a promise that is already there.

It is considered an anti-pattern to have do-nothing success and error handlers that just do basically what the default behavior would already be.

Really, the only thing that your code snippet does differently than just returning the promise directly is that it makes sure the returned promise is a Q promise, not whatever kind of promise .someFunction() returns. But, if that is a requirement, then it could be cast to a Q promise more directly without all the extra code.

Here's a discussion of promise anti-patterns to be avoided because there's a better way.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
2

There is no reason why you would use a deferred promise in your case. In fact using defer is one of the most common anti-patterns when using promises and should only be used in very specific cases.

In Deferred anti-pattern, "deferred" objects are created for no reason, complicating code.

This superfluous wrapping is also dangerous, any kind of errors and rejections are swallowed and not propagated to the caller of this function.

Instead of using the Deferred anti-pattern, the code should simply return the promise it already has and propagate values using return

Have a quick read over at the bluebird (one of the best promises libraries) docs where this topic is discussed https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern

masimplo
  • 3,674
  • 2
  • 30
  • 47