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

时间:2016-07-13 10:59:31

标签: javascript jquery asynchronous

不确定如何在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..
}

1 个答案:

答案 0 :(得分:1)

$.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..
}