【发布时间】:2021-02-10 18:25:36
【问题描述】:
我是异步等待的新手,我不确定它是否像我想的那样工作。搜索结果尚无定论,我需要有人为我指明正确的方向。
我有两个函数,addOrder(),它调用 getDistance() 函数来执行一些 api 工作,然后在我的数据函数(vue 应用程序)中设置“里程”。但是,似乎等待不起作用,就好像我在等待 getDistance 函数后立即尝试控制台记录“里程”一样,它仍然显示为空(它被初始化为什么)。任何见解都值得赞赏。
添加订单功能:
async addToOrder(){
await this.getDistance()
console.log(this.mileage) //problem is here, it shows the initialized value instead of the value changed in getDistance
}
获取距离函数
async getDistance() {
var origin = `${this.pickupPair.lat},${this.pickupPair.lng}`
var dest = `${this.dropoffPair.lat},${this.dropoffPair.lng}`
let miles
//using google maps loader
loader.load().then(() => {
const service = new google.maps.DistanceMatrixService()
service.getDistanceMatrix(
{
origins: [origin],
destinations: [dest],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false,
},
(response, status) => {
if (status !== 'OK') {
alert('Error was: ' + status)
} else {
const originList = response.originAddresses
const destinationList = response.destinationAddresses
this.mileage = response.rows[0].elements[0].distance.text
this.mileage = this.mileage.replace(' mi', '')
this.getCost()
}
}
)
})
}
【问题讨论】:
-
等待 this.getDistance().then(res=>console.log(res)) ?看起来你没有用 getDistance 返回任何东西?我知道的模式是你抓取数据,然后返回它——然后你在得到响应后操作对象,如果你在回调中操作东西——“this”关键字会变得很奇怪。
标签: javascript asynchronous async-await