我有一个想要传递给函数并进行操作的对象,名为 spots
我的 setDistances
函数就是这样做的。
在函数之后,我将 console.log
操作值,如下所示 console.log('DistanceFrom Set. ' + distSetSpots[0].distanceFrom);
&看起来该值尚未更改。
奇怪的是,如果我像这样 console.log
整个对象 console.log(distSetSpots);
并通过 chrome 开发工具而不是以编程方式横向穿过它,它实际上会显示被操纵的值。
这让我很困惑..任何人都可以解释这里发生了什么吗?完整相关代码如下:
// Get a copy of the Spots data in spots.json
this.sds.fetchData( (spots) => {
// Get distance inbetween each spot & the user's location
this.lcs.setDistances(spots, (distSetSpots) => {
console.log(distSetSpots);
console.log('DistanceFrom Set. ' + distSetSpots[0].distanceFrom);
// 'Filter' spots (set 'pts' to null) that exceed max distance
this.filterFarSpots(distSetSpots, (filteredSpots) => {
// Find matched target species in spots & assign pts
this.findTargetSpecies(filteredSpots, (prefTargSpots) => {
});
});
});
}
);
设置距离函数:
setDistances(spots, callback) {
const posRef = this.posObject;
for (let i = 0; i < spots.length; i++) {
const origin = new google.maps.LatLng(posRef.pos.coords.latitude, posRef.pos.coords.longitude);
const destination = new google.maps.LatLng(spots[i].coords[0], spots[i].coords[1]);
const service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
}, (resp, status) => {
spots[i].distanceFrom = (resp.rows[0].elements[0].distance.value / 1000).toFixed(1);
});
}
callback(spots);
}
最佳答案
正如评论中所述,我的 setDistances
函数在有任何响应之前使用了callback
。感谢 Paulpro 消除了我所遇到的 console.log
困惑。这是我解决问题的方法:
我删除了通过 getDistanceMatrix
发出请求的 for 循环
,并将其替换为自调用函数调用,以及条件语句和 count
变量来跟踪每个单独的请求,当所有请求完成时,它还会调用回调
。代码如下:
(resp, status) => {
spots[this.count].distanceFrom = (resp.rows[0].elements[0].distance.value / 1000).toFixed(1);
if ((this.count + 1) < spots.length) {
this.count++;
this.setDistances(spots, callback);
} else {
this.count = 0;
callback(spots);
}
});
关于javascript - 异步对象操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040056/