Binding a promise handler function to an object

后端 未结 4 998
迷失自我
迷失自我 2020-12-18 19:21

I have some code like:

var bar = foo().then(function success(value) {
  // compute something from a value...
}, function failure(reason) {
  // handle an err         


        
4条回答
  •  春和景丽
    2020-12-18 19:48

    You currently have an anonymous (although labelled) function for your failure callback:

    function failure(reason) {
       // handle an error...
    }
    

    As robertklep says, you can immediately call .bind on that anonymous function. However, it might be more readable to use a named function instead, and pass it into .then() as a variable:

    function success(value) {
        // compute something from a value...
    }
    function failure(reason) {
        // handle an error...
    }
    var bar = foo().then(success, failure.bind(this));
    

提交回复
热议问题