异步对象操作

问题描述 投票:0回答:2

我有一个对象,我想传递给函数和操作称为spots

我的setDistances功能就是这样。

在函数之后,我将console.log像这个console.log('DistanceFrom Set. ' + distSetSpots[0].distanceFrom);这样的操纵值,它似乎没有被改变。

奇怪的是,如果我console.log整个对象像这个console.log(distSetSpots);&横穿它通过chrome dev工具而不是programactically,它实际上将显示被操纵的价值。

这让我很困惑..任何人都可以解释这里发生的事情吗?完整相关代码如下:

    // 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函数:

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);
}
javascript angular asynchronous callback
2个回答
2
投票

正如评论中所述,我的setDistances函数在有任何回复之前使用callback。感谢Paulpro清理了我所遇到的console.log混乱。以下是我如何解决我的问题:

我删除了通过for loop发出请求的getDistanceMatrix并将其替换为自调用函数调用,以及条件语句和count变量以跟踪每个单独的请求,当所有请求都完成时,它也调用callback。代码如下:

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

-1
投票

试着把callback(spots)召唤到这个地方:

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

问题是你的回调(..)是在map回调之前执行的。因此,在调用spots时,callback(spots)数据尚未确定。

© www.soinside.com 2019 - 2024. All rights reserved.