簡體   English   中英

從回調中獲取值 function

[英]getting a value from a callback function

我正在嘗試從回調 function 返回一個值並將其分配給一個變量,盡管我正在努力解決它 - 任何幫助都會非常感激......

var latlng1;

function getLocation(){
  navigator.geolocation.getCurrentPosition (function (position){
    coords = position.coords.latitude + "," + position.coords.longitude;
    callback();         
  })
}

//how can I assign the coords value from the callback to variable latlng1 with global scope?
getLocation (function(){
  //alert(coords);
  return coords;
})

// -----------
//I'm trying something like this....but no joy
latlng1 = getLocation (function(){
  return coords;
}

我很困惑,您是否希望回調能夠訪問coords值,或者只是從getLocation function 返回它。如果只是讓coords可用於回調,則將其作為參數傳遞。

function getLocation(callback) {
  navigator.geolocation.getCurrentPosition (function (position){
    var coords = position.coords.latitude + "," + position.coords.longitude;
    callback(coords);         
  })
}

getLocation (function(coords){
  alert(coords);
})

另一方面,如果要將它分配給getLocation的返回值,那是不可能的。 getCurrentPosition API 是異步的,因此您不能從getLocation方法同步返回它。 相反,您需要傳回想要使用coords的回調。

編輯

OP 說他們只想要latlng1中的coords值。 這是你如何做到這一點

var latlng1;
function getLocation() {
  navigator.geolocation.getCurrentPosition (function (position){
    var coords = position.coords.latitude + "," + position.coords.longitude;
    latlng1 = coords; 
  })
}

請注意,盡管這不會更改 API 的異步性質。在異步調用完成之前,變量latlng1不會具有coords值。 因為這個版本不使用回調你無法知道什么時候完成(除了檢查latlng1 undefined

怎么樣:

var latlng1;

function getLocation(){
  navigator.geolocation.getCurrentPosition (function (position){
    latlng1 = position.coords.latitude + "," + position.coords.longitude;
    callback();         
  })
}

getLocation (function(){
  alert(latlng1);
})

您可以將坐標傳遞給回調調用,並在回調中為其定義一個參數。 閱讀比嘗試解釋更容易:

var latlng1;

function getLocation(callback){
  navigator.geolocation.getCurrentPosition (function (position){
    coords = position.coords.latitude + "," + position.coords.longitude;
    callback(coords);         
  })
}

//how can I assign the coords value from the callback to variable latlng1 with global scope?
getLocation (function(coords){
  //alert(coords);
  return coords;
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM