0

I understand what is The deferred antipattern, also mentioned as "The Forgotten Promise" HERE.

I also read: what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it.

Anyways I should try to get rid of using $q.defer().

But I don't understand how to handle case where I got response and I need to reject it because it doesn't have proper key.

This is my method in Service that returns promise to controller.

self.findTime = function(data){

  var deferred = $q.defer();

   apiClient.findTime(data)
      .then(function (response) {

         if (response.result !== "success") {
            deferred.reject(response);
         }

        deferred.resolve(response);
      }
      , function (error) {
      deferred.reject(error);
        console.error(error);
      });

      return deferred.promise;
};

So I tried to change it to:

self.findTime = function(data){      

   return apiClient.findTime(data)
      .then(function (response) {

         if (response.result !== "success") {
            // return WHAT ??? <-------------
         }
        return response;
      }
      , function (error) {
      // return WHAT ??? <-------------
        console.error(error);
   });
};

How to handle reject?

In controller, on reject I show some morning message.

 Service.findTime(data).then(function (response) {
   // do something
    }, function (error) {
      // show warn dialog
 });
snaggs
  • 5,543
  • 17
  • 64
  • 127

1 Answers1

1

You have two options.

You can return a rejection promise from within your resolve:

return apiClient.findTime(data)
    .then(function (response) {
        if (response.result !== "success") {
            return $q.reject('reason'); // Convert to rejection
        }
        return response;
    }, function (error) {
        console.error(error);
        return $q.reject('reason');  // Chain rejection
    });

or you can throw an exception:

return apiClient.findTime(data)
    .then(function (response) {
        if (response.result !== "success") {
            throw new Error('reason');
        }
        return response;
    }, function (error) {
        console.error(error);
        throw new Error(error);
    });
Nikolaj Dam Larsen
  • 5,455
  • 4
  • 32
  • 45