gpt4 book ai didi

javascript - 无法达到某个值......ReactJS

转载 作者:行者123 更新时间:2023-12-03 02:13:55 25 4
gpt4 key购买 nike

我目前在访问函数内的值时遇到问题。

这是我的代码:

distanceBool = (event) => {
console.dir(event);

let address = ["Toronto, ON, CA"];

let destination = ["Vancouver"];

let location = this;

let service = new window.google.maps.DistanceMatrixService();
new Promise((resolve)=>{
resolve(
service.getDistanceMatrix({
origins: ["Waterloo ON"],
destinations: destination,
travelMode: 'DRIVING',
avoidHighways: false,
avoidTolls: false
}, function(response, status){
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;

for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];

location.distFinal = distance;

location.setState({
dist: distance
})

}
}

}
})

)
}).then((res)=>{
// console.log(res)
// console.dir(location);
console.dir(location);
console.dir(location.distFinal);
// console.log("hello")
})


}

我正在尝试访问距离,因此我执行了 console.dir(location.distFinal) 但它给了我一个未定义的值。但是,当我执行 console.dir(location) 时,它给了我以 distFinal 作为值的对象......

这就是我的意思:

enter image description here

第132行是console.dir(location),第133行是console.dir(location.distFinal)

拜托!我只是想能够提取距离!

最佳答案

您的顶级 promise 立即解决 - 您可能只想在内部异步代码完成后才解决。

new Promise((resolve)=>{
service.getDistanceMatrix({
origins: ["Waterloo ON"],
destinations: destination,
travelMode: 'DRIVING',
avoidHighways: false,
avoidTolls: false
}, function(response, status){
if (status !== 'OK') return;
var origins = response.originAddresses;
var destinations = response.destinationAddresses;

for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];

location.distFinal = distance;
location.setState({
dist: distance
})
}
}
// all the looping is done:
resolve();
})
}).then((res)=>{
// console.log(res)
// console.dir(location);
console.dir(location);
console.dir(location.distFinal);
// console.log("hello")
})

关于javascript - 无法达到某个值......ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49441583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com