在对象文本方法周围传递异步值

Passing async values around object literal methods

本文关键字:异步 周围传 对象 文本方法      更新时间:2023-09-26

不确定如何在getLocations方法之外传递getLocationsArray的返回值。如何做到这一点setMarkers以便方法可以使用它?当然,我知道在对象文字内部调用方法或变量时,例如我可以使用APP.map.setMarkers。谢谢。

 init: function(){
   ...ETC...
  APP.map.getLocations()
  APP.map.setMarkers(center, radius, map)
},
getLocations: function() {
  $.getJSON('data/json/locations.json', function(data) {
    var locations = data
    var getLocationsArray = $.map(locations, function(value, index) {
      return [value]
    })
    console.log(getLocationsArray)
    return getLocationsArray
  })
  console.log('getLocationsArray2', getLocationsArray2)
  return getLocationsArray2
},
setMarkers: function(center, radius, map) {
  **getLocationsArray**.forEach (function (hello) {
  ..ETC..
}
$.getJSON只会

异步提供其结果,因此您不能使用期望它立即可用的代码。而是使用回调系统。

$.getJSON 回调函数中返回一个值是没有用的:它将被遗忘:

 return getLocationsArray // not useful.

您还引用从未初始化的变量getLocationsArray2

相反,您可以传递一个回调参数:

init: function(){
  // ...ETC...
  // Pass an (anonymous) callback function to `getLocations`, which
  // it will call when the result is available. Then you can call
  // `setMarkers` to process that result.
  APP.map.getLocations(function (getLocationsArray) {
      APP.map.setMarkers(getLocationsArray, center, radius, map);
  });
},
getLocations: function(callback) {
  $.getJSON('data/json/locations.json', function(data) {
    var locations = data
    var getLocationsArray = $.map(locations, function(value, index) {
      return [value]
    })
    // If a callback function was provided, then call it now and
    // pass it the result.
    if (callback) callback(getLocationsArray);
  })
},
setMarkers: function(getLocationsArray, center, radius, map) {
  // We get the locations array as an argument now, so it is straightforward
  // to process it:
  getLocationsArray.forEach (function (hello) {
     ///..ETC..
}