我目前正在使用here-api制作路由系统。我从文本方向的数组开始。像这样。
directions: [
"2 Rue de l'Euron, 54320 Maxéville",
"34 Rue Sainte-Catherine, 54000 Nancy", //aquarium
"401 Avenue de Boufflers, 54520 Laxou", //grand frais
"42 Rue Kléber, 54000 Nancy", //regalo pizza
"33/45 Avenue de Metz, 54320 Maxéville", //lidl
"2 Rue de l'Euron, 54320 Maxéville"
]
我将这些指示发送到here API,以获取这些指示的经纬度。问题是我使用了promise,有时这些指示以不同的顺序返回,但是我至少需要第一个和最后一个保持原样。
我已经读过this和this。我已经尝试过使用await,但是我不能,因为它是一个异步函数。没有承诺但它说需要回调。
这就是我通过此处的地址解析器获取坐标
getCoordinates(query) {
return new Promise((resolve, reject) => {
this.geocoder.geocode({ searchText: query }, data => {
//Si il y'a une response
if(data.Response.View[0].Result.length > 0) {
data = data.Response.View[0].Result.map(location => {
return {
address: query,
lat: location.Location.DisplayPosition.Latitude + "", //.toString() marche pas
lng: location.Location.DisplayPosition.Longitude + ""
};
});
resolve(data);
}
//Si non
else {
reject({ "message": "No data found" });
}
}, error => {
reject(error);
});
});
},
在这里,我尝试在onLoad上接收它们
load(directions){
directions.map(direction =>
this.getCoordinates(direction).then(response =>
console.log(response[0]))
)
}
有时候我会有这样的回应。未订购
{address: "2 Rue de l'Euron, 54320 Maxéville", lat: "48.70283", lng: "6.13316"}
{address: "401 Avenue de Boufflers, 54520 Laxou", lat: "48.69347", lng: "6.13732"}
{address: "33/45 Avenue de Metz, 54320 Maxéville", lat: "48.70848", lng: "6.16666"}
{address: "2 Rue de l'Euron, 54320 Maxéville", lat: "48.70283", lng: "6.13316"}
{address: "34 Rue Sainte-Catherine, 54000 Nancy", lat: "48.69507", lng: "6.18847"}
{address: "42 Rue Kléber, 54000 Nancy", lat: "48.68373", lng: "6.16838"}
答案 0 :(得分:2)
仅在对每个方向的映射承诺上调用Promise.all
后才记录响应:
load(directions){
Promise.all(
directions.map(direction => this.getCoordinates(direction))
)
.then((coordinates) => {
coordinates.forEach((coordinate) => {
console.log(coordinate);
});
});
}
Promise.all
将一个Promises数组作为参数,并解析为每个Promise解析值的一个数组,与原始数组的顺序相同-这正是您想要的