需要帮助来了解此javascript变量的范围

时间:2020-01-03 07:31:19

标签: javascript google-maps vue.js google-maps-api-3 scope

在javascript中的VueJS SPA中,我正在尝试创建一种方法,该方法将通过仅将place_id和我想返回的字段传递给Google Maps Places Service来减少冗余代码。

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 ..,但位置为null。我尝试使用

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
  })
}

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

2 个答案:

答案 0 :(得分:0)

您可以考虑将JSON分配给受Vue监视的数据变量,而不是return,像这样:

    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...]

答案 1 :(得分:0)

承诺

promise是一个将来会解决(或拒绝)的对象。这对于执行异步任务(例如http-calls)来说是必要的,而异步任务需要花费不确定的时间才能完成。

承诺可以链接,即一个接一个地执行。这就是.then方法的作用。使用.then传递了一个函数,该函数将在诺言完成后立即执行。该函数将接收上一个诺言返回的对象。

您的方法

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;
            }
        });
    });
}

此方法将返回一个承诺-在将来的某个时刻-将产生期望的结果。

当您要调用该方法时,您将得到该诺言并必须处理该诺言,再次通过传递一个函数(使用.then),该函数将在结果准备好后执行。

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

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