0

In a controller I have this function:

bar.updateData = function(val) {
    $http.put('url/foo/', {
        param   : val
    }).success(function(data){
        return true;
    }).error(function(data){
        return 'this is a string';
    });
};

I need to return true or a string depending on the callback success() or error(). I wrote that code but seems not working.

1 Answer 1

3

Accepted answer is right but also wrong (it gives you the correct code but doesn't explain the reasoning as to why this won't work). $http.put does return a promise that gives you success and error callbacks. The information in that answer is just flat out incorrect.

You can't return values from success and error because they are callbacks and not part of the A+ promise standard. They do not chain, because they do not return a new promise each time you invoke them, they instead return the same promise.

For this reason, you should more-or-less always use then/catch - both of these play well with other non-$http promises and are standard methods. They also support chaining because then and catch will return a new version of the promise with each subsequent invocation - so the return value from the first then will be passed to the second then (and so forth).

The code that @Pankaj has posted is more or less correct, I would make a minor modification and use catch instead of passing two callbacks to then because it is easier to scan.

bar.updateData = function(val) {
  return $http.put('url/foo', { param: val })
    .then(function(res) {
      return res.data;
    })
    .catch(function(error) {
      return 'this is a string';
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.