Javascript assigning the return value of a Callback function to global variable

后端 未结 5 1226
北海茫月
北海茫月 2020-12-28 19:01

My question is about Javascript. I have a Callback function which receives a Position object on a successful callback.

The problem is that when I try to set the prop

相关标签:
5条回答
  • 2020-12-28 19:13

    You can't return a value from the callback (in this case). That would mean that inside of getCurrentPosition, the return value from the callback has to be assigned somewhere.

    Assigning it to a global variable works, but at the time you access that variable, it was not assigned the new value yet. E.g.

    // x is assigned in `onSuccess`
    var x;
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
    alert(x); // will be undefined, the response is not processed yet
    

    Think about it: getCurrentPosition is probably doing an Ajax request to get the position. Such a request takes (a) time (couple of milliseconds) and because of that (b) is asynchronous, which means that JavaScript does not wait until the response is received. Your code is way faster. onSuccess was not called yet when you alert x.

    Only solution:

    All the code that has to access the position as to be in or called from the callback.

    0 讨论(0)
  • 2020-12-28 19:21

    have you tried setting it via the global window object?

    //on Successful callback receives a Position Object
    function onSuccess(position) {  
      var coords = position.coords;  
        window.x=coords;       // Setting directly to an object does not work x still remains undefined after succesful callback               
    return coord; // Trying to set this to a global object 
    
    }
    

    also, since you return the coordinates from the success handler, is there not another way to get this value?

    0 讨论(0)
  • 2020-12-28 19:22

    As described by Felix King, you cannot return a value from a callback and in your global variable variant, the variable will not be set until after the AJAX request completes and calls the callback (hence its name !).

    Using a global variable you can solve your problem if you have some sort of processing loop, you can add this code to that loop to do what is required whenever the coord changes.

      if (coord) // global variable has a new value
        // process it
         alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
        // then clear it
        coord = null;
      } 
    
    0 讨论(0)
  • 2020-12-28 19:28

    You can implement a helper method like flowing:

    var LocationHelper = function() {};
    
    LocationHelper.prototype.getLocation = function(callback) {
    
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    
        function onSuccess(pos) {
            callback({
                pos: pos
            });
        }
    
        function onError(message) {
            callback({
                message: message
            });
        }
    
      };
    
    0 讨论(0)
  • 2020-12-28 19:29

    put a console.log(x); just after x=cords to check the value (works on Chrome and FF with FireBug)

    do that also just after the call of OnSuccess.

    Also don't forget that there is asynchronous code in JS (if you use AJAX to get the position), maybe you just don't receive the answer when you check the value of x

    0 讨论(0)
提交回复
热议问题