循环通过 mapbox getDirections 来填充路由数组

loop through mapbox getDirections to populate a route array

我试图遍历一个名为 directions 的数组,每个索引包含两个数组,索引 1 处的纬度和索引 0 处的经度,并将 mapbox.getDirections 的结果添加到路线数组以绘制路线地图。下面是我的代码:

我认为我面临同步性问题并且 mapbox.getDirections 回调没有及时响应,所以如果路由大于 1,我会得到奇怪的路由。

for (let i = 0; i < directions.length - 1; i++) {
                let fromIndex = i;
                let toIndex = fromIndex + 1;
                let directionParams = [
                    { latitude: directions[fromIndex][1], longitude: directions[fromIndex][0] },
                    { latitude: directions[toIndex][1], longitude: directions[toIndex][0] }
                ]
                let self = this;
                mapbox.getDirections(directionParams, getDirectionsParams).then(function (results) {
                    let routes = results.entity.routes[0].geometry.coordinates;
                    let newRoute = self.state.route.concat(routes);
                    self.setState({
                        route: newRoute,
                    })
                });
            }

这个方法应该是数组大小不可知的,所以如果数组是 4 个索引,它将提取从索引 0 到 1、1 到 2、2 到 3 的方向,因此总共显示 3 条路线。

分离逻辑,可以把promise移到循环外,和Promise.All

一起解决

const yourFunction = async () => {

  const arrayOfDirections = [];
  for (let i = 0; i < directions.length - 1; i++) {
    const fromIndex = i;
    const toIndex = fromIndex + 1;
    const directionParams = [
      { latitude: directions[fromIndex][1], longitude: directions[fromIndex][0] },
      { latitude: directions[toIndex][1], longitude: directions[toIndex][0] }
    ];
    arrayOfDirections.push(directionParams);
  }

  const promises = [];
  arrayOfDirections.forEach((directionParams) => {
    promises.push(mapbox.getDirections(directionParams, getDirectionsParams));
  });

  const arrayOfresults = await Promise.all(promises);
   // here you have array of results returned by your promises
};