[removed] Passing parameters to a callback function

后端 未结 13 2458
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 15:48

I\'m trying to pass some parameter to a function used as callback, how can I do that?

function tryMe (param1, param2) {
    alert (param1 + \" and \" + param         


        
13条回答
  •  忘掉有多难
    2020-11-22 16:10

    A new version for the scenario where the callback will be called by some other function, not your own code, and you want to add additional parameters.

    For example, let's pretend that you have a lot of nested calls with success and error callbacks. I will use angular promises for this example but any javascript code with callbacks would be the same for the purpose.

    someObject.doSomething(param1, function(result1) {
      console.log("Got result from doSomething: " + result1);
      result.doSomethingElse(param2, function(result2) {
        console.log("Got result from doSomethingElse: " + result2);
      }, function(error2) {
        console.log("Got error from doSomethingElse: " + error2);
      });
    }, function(error1) {
      console.log("Got error from doSomething: " + error1);
    });
    

    Now you may want to unclutter your code by defining a function to log errors, keeping the origin of the error for debugging purposes. This is how you would proceed to refactor your code:

    someObject.doSomething(param1, function (result1) {
      console.log("Got result from doSomething: " + result1);
      result.doSomethingElse(param2, function (result2) {
        console.log("Got result from doSomethingElse: " + result2);
      }, handleError.bind(null, "doSomethingElse"));
    }, handleError.bind(null, "doSomething"));
    
    /*
     * Log errors, capturing the error of a callback and prepending an id
     */
    var handleError = function (id, error) {
      var id = id || "";
      console.log("Got error from " + id + ": " + error);
    };
    

    The calling function will still add the error parameter after your callback function parameters.

提交回复
热议问题