Use Promise.all
to wait for each Station promise to resolve:
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)
});
The inner Promise.all
isn't necessary, but it helps constrain the scope - equivalently, you could do:
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)
});
Thanks @jonrsharpe, a much nicer-looking approach would just chain a .then
onto the getDistance
promise:
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);