перебрать getDirections в mapbox, чтобы заполнить массив маршрутов - PullRequest
1 голос
/ 01 апреля 2019

Я пытаюсь перебрать массив, называемый направлениями, каждый индекс, содержащий два массива, широту с индексом 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 маршрута.

1 Ответ

1 голос
/ 01 апреля 2019

Разделив логику, вы можете переместить обещания за пределы цикла и разрешить их все вместе с помощью 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
};

...