why this JavaScript method return undefined?

前端 未结 3 2055
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 08:33

in this code this method return undefined despites alert statement print a value ?

function getNearestPoint(idd) 
        {
            var xmlhttp;
                     


        
相关标签:
3条回答
  • 2021-01-24 08:43

    result isn't defined at that point, it only gets defined once your callback executes. The order of execution:

    • getNearestPoint starts
    • XHR is fired off
    • getNearestPoint returns undefiend
    • XHR comes back and runs xmlhttp.onreadystatechange
    • result gets set

    If you need result from OUTSIDE of this, you should use a callback:

    getNearestPoint(idd, cb){
       ...
       xmlhttp.onreadystatechange = function(){
          ...
          cb(result);
       }
    }
    

    and your calling code changes from:

    var result = getNearestPoint(id);
    

    to:

    getNearestPoint(id, function(result){
       // do something with result;
    });
    
    0 讨论(0)
  • 2021-01-24 09:02

    result setting statement executes inside async Ajax function

    Because your second if statement (that sets result value) doesn't get hit. Why not? Because the moment you send an Ajax request you return the result value which is still undefined. Ajax call will execute the anonymous function later on and set this result variable which has been returned long ago.

    Ajax is asynchronous and your code isn't taking this into account.

    0 讨论(0)
  • 2021-01-24 09:02

    This is because of the asychronous nature of Ajax ("Asynchronous JavaScript and XML"): The request will still be running when your code hits return result. The readystatechange callback will not have been called yet, and the result variable not set yet.

    The usual way to deal with this is to change the architecture of the script: Do whatever you need to do based on result directly in the onreadystatechange callback. (or, of course, pass a callback function with the desired actions and execute it in the handler.)

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