我正在尝试映射一个数组,我想使用扩展语法向该数组添加一个字段。我想用于每个元素的数据来自api调用。我正在尝试获取价值而不是承诺。
这就是我现在得到的:
distance: Promise { <state>: "fulfilled", <value>: (1) […] }
id: "1234"
应该是:
distance: 5
id: "1234"
这是我正在使用的代码:
let stations = nearestStations.map(station => ({
...station,
distance: getDistance([userLocation[0], userLocation[1]], [station.lat,station.lon]).then(_=>_)
}))
console.log(stations)
答案 0 :(得分:1)
使用Promise.all
等待每个Station承诺解决:
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);