Используйте Promise.all
, чтобы дождаться разрешения каждой станции:
const userLatLon = [userLocation[0], userLocation[1]];
const stationProms = nearestStations.map(
// use Promise.all here so that the station can be passed along with its `distance` promise
station => (Promise.all([station, getDistance(userLatLon, [station.lat,station.lon])]))
);
Promise.all(stationProms).then((stationItems) => {
const stations = stationItems.map(([station, distance]) => ({ ...station, distance }));
console.log(stations)
});
Внутренний Promise.all
не нужен, но он помогает ограничить область действия - эквивалентно, вы можете сделать:
const userLatLon = [userLocation[0], userLocation[1]];
const stationProms = nearestStations.map(station => getDistance(userLatLon, [station.lat,station.lon]));
Promise.all(stationProms).then((stationItems) => {
const stations = stationItems.map((distance, i) => ({ ...nearestStations[i], distance }));
console.log(stations)
});
Благодаря @jonrsharpe, гораздо более привлекательный подход просто связал бы .then
с getDistance
обещанием:
const userLatLon = [userLocation[0], userLocation[1]];
const stationProms = nearestStations.map(
station => getDistance(userLatLon, [station.lat,station.lon])
.then(distance => ({ ...station, distance }))
);
Promise.all(stationProms).then(console.log);