0

I have a controller which calls the api.

$scope.getUserDetails = function(){

    var promise = userService.getPromise();

    promise.then(function(user){
        if(user.error){
            //handle error
        } else {
            //perform other task
        }
    }.bind(this));

};

but I am not able to understand that what does this bind function do.

1
  • 1
    Seems like more code is needed to be sure why that's there. bind(this) sets the context of the function it is called on, so if this is used inside that function, it will refer to this that was passed to bind. Perhaps there is some code inside of that function that would call this and this needs to be set correctly. It's all a bit awkward. There's probably a better way to do whatever is trying to be done there. Commented Sep 1, 2015 at 5:33

1 Answer 1

1

According to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

so in your case when promise is resolved your callback function will have this set to your controller.

Sign up to request clarification or add additional context in comments.

2 Comments

Might want to also add that since this is actually not used in the function that bind is not actually required in this case.
@WayneEllery Yes your right. But his question is regarding use of bind() function!!

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.