需要帮助理解这个 javascript 变量的范围

Need help understanding the scope of this javascript variable

在 javascript 中,在 VueJS SPA 中,我试图创建一种方法,通过仅向 Google Maps Places 服务传递 place_id 和我想要的字段 returned.

getPlaceDetails (place, fields) {
  this.$refs.mapRef.$mapPromise.then((map) => {
    var placesServices = new window.google.maps.places.PlacesService(map)
    placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
      if (status === window.google.maps.places.PlacesServiceStatus.OK) {
        alert(JSON.stringify(result))
        return result
      }
    })
  })
}

我正在从另一个方法中调用上述方法:

var place = this.getPlaceDetails(place, ['name', 'geometry', 'place_id'])

它已成功调用...并且警报显示所需的 JSON.. 但位置为空。我试过使用

var vm = this

以上

var placesServices

并将结果分配给应用程序级变量...甚至在 .then 中,在第一个承诺之后...像这样:

getPlaceDetails (place, fields) {
  this.$refs.mapRef.$mapPromise.then((map) => {
    var vm = this
    var placesServices = new window.google.maps.places.PlacesService(map)
    placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
      if (status === window.google.maps.places.PlacesServiceStatus.OK) {
        alert(JSON.stringify(result))
        vm.tempPlace = result
      }
    })
  }).then(function () {
    return this.tempPlace
  })
}

如何获取 return 结果对象的方法??

您可以考虑将 JSON 分配给 Vue 监视数据变量,而不是 returning 数据,如下所示:

    var somePlace = new Vue({
      el: '#someEl',
      data: {
        message: 'Hello robwolf.io',
        tempPlace: {} // <- variable waiting for your asynchronous data if it comes thru
      },
      methods: {
      getPlaceDetails (place, fields) {
        // [...your promise code here...]
        }).then((result) => {
           this.tempPlace = JSON.stringify(result)
           // return this.tempPlace
        })
  // [...the .then function must also be an arrow function to have scope access to tempPlace...]

承诺

A promise 是一个将在未来某个时间解析(或拒绝)的对象。这对于执行需要未定义的时间量才能完成的异步任务(例如 http 调用)是必要的。

Promise 可以链接 即一个接一个地执行。这就是 .then 方法的作用。使用 .then 传递一个函数,该函数将在 promise 完成后立即执行。此函数将接收由先前的承诺 return 编辑的对象。

你的方法

getPlaceDetails (place, fields) {
    return this.$refs.mapRef.$mapPromise.then((map) => {
        var vm = this;
        var placesServices = new window.google.maps.places.PlacesService(map);
        placesServices.getDetails({ placeId: String(place.place_id), fields: fields }, (result, status) => {
            if (status === window.google.maps.places.PlacesServiceStatus.OK) {
                alert(JSON.stringify(result));
                return result;
            }
        });
    });
}

此方法将 return 承诺 - 在未来的某个时候 - 将产生所需的结果。

当你想调用方法时,你得到了那个承诺并且必须处理它,再次通过传递一个函数(使用 .then),一旦结果准备好就会执行。

this.getPlaceDetails(...).then((result) => {
    // handle your result
}}

或者,您可以使用 await operator 等待 promise 完成: var place = await this.getPlaceDetails(...);