Search code examples
javascriptpromiseqdeferred

Should I return the result of deferred.resolve/reject?


When working with Q deferreds, should I return the result of deferred.resolve and deferred.reject?

function foo() {
  var deferred = Q.defer();
  service.doSomethingAsync({
    success: function() {
      deferred.resolve(); // should I return the result of resolve here?
    }, 
    fail: function(err) {
      deferred.reject(err); // should I return the result of reject here?
    }
  });

  return deferred.promise;
}

Solution

  • Your code can be changed to:

    function foo() {
      var deferred = Q.defer();
    
      service.doSomethingAsync({
        success: deferred.resolve, 
        fail:  deferred.reject
      });
    
      return deferred.promise;
    }
    

    What you want to return from the foo() method depends on what you want to achieve of course. In many cases you hide the internals and just return an empty array or null if something fails. But..if it is needed...you can throw an error. If you want to handle things outside the function, yes, return the error object for example...like I said...it depends.