繁体   English   中英

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

[英]Need help understanding the scope of this javascript variable

在 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..但地方为空。 我试过使用

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

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

您可以考虑将 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...]

承诺

承诺是在未来的某个时间点解决(或拒绝)的对象。 这对于执行需要不确定的时间来完成的异步任务(例如 http 调用)是必要的。

Promise 可以链接起来,即一个接一个地执行。 这就是.then方法所做的。 使用.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 运算符等待承诺完成: var place = await this.getPlaceDetails(...);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM