在分布图中使用承诺

时间:2019-06-03 07:10:45

标签: javascript dictionary promise

我正在尝试映射一个数组,我想使用扩展语法向该数组添加一个字段。我想用于每个元素的数据来自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)

1 个答案:

答案 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);