variable scope in asynchronous function

后端 未结 2 1877
[愿得一人]
[愿得一人] 2021-01-21 01:15

I\'ve built the function to return some variable. But my function uses another function asynchronously.

function getVariable() {
  var myVariable;
  asyncronousF         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-21 01:57

    They are not different variables, it is the same variable... but you haven't assigned a value to myVariable before you return it at the end of the function.

    The correct pattern here would be for getVariable and asychronousFunction to accept callbacks, which are executed when the asynchronousFunction has finished executing.

    function getVariable(callback) {
      var myVariable;
      asyncronousFunction(function(/* pass callback as one of the parameters */){
    
        myVariable = ...
    
      });
    
      // Don't return myVariable, as it's useless at this point
    };
    
    function asyncronousFunction(callback) {
       // This simulates the asynchronous call. When the call finishes, invoke callback and pass the result as a parameter.
       setTimeout(function () {
            callback("result");
       }, 1000);
    }
    

    You should then edit how you use the function getVariable().

    So where you might have had:

    var value = getVariable();
    // do whatever with value
    value++;
    

    You should now have:

    getVariable(function (value) { // value is now passed as a parameter
        value++;
    });
    

提交回复
热议问题