why this JavaScript method return undefined?

前端 未结 3 2091
没有蜡笔的小新
没有蜡笔的小新 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;
    });
    

提交回复
热议问题