我试图遍历一个称为Directions的数组,每个索引包含两个数组,即索引1处的纬度和索引0处的经度,并将mapbox.getDirections的结果添加到route数组以在地图上绘制路线。下面是我的代码:
我认为我遇到了同步性问题,并且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条路线。
答案 0 :(得分:1)
分离逻辑,您可以将承诺移出循环,并与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
};