簡體   English   中英

在 Promise.all 中使用 .map

[英]Using .map in Promise.all

所以,我有一些承諾需要在我的 Express Server 中的 init 上運行。

const dates = [];
for (var i = 0; i <= 8; i++) {
  dates.push(
    moment()
      .add(i, "days")
      .format("YYYY-MM-DD")
  );
}
const [cityName, weatherData, celestialData] = await Promise.all([
  axios.get(
    `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${myKey}`
  ),
  axios.get(
    `https://api.darksky.net/forecast/${myKey}/${latitude},${longitude}`
  ),
  dates.map(date => {
    axios.get(
      `https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`
    );
  })
]);

我需要來自 8 個不同日期的數據,所以我想通過運行帶有日期數組的 .map 我會得到另一個數組,每個數組都有已解決的承諾。 這不像我預期的那樣工作。 如何管理 Promise.all 中的循環 axios 調用?

你真的很親近。 你想要

  1. dates.map展開數組
  2. 在您的解構過程中捕獲其余元素中的結果
  3. map回調中返回axios的結果

大致:

const [cityName, weatherData, ...celestialData] = await Promise.all([
// 2 −−−−−−−−−−−−−−−−−−−−−−−−−^^^
  axios.get(
    `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${myKey}`
  ),
  axios.get(
    `https://api.darksky.net/forecast/${myKey}/${latitude},${longitude}`
  ),
  ...dates.map(date => {
//^^^−−−− 1
    return axios.get(
//−−^^^^^^ 3
      `https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`
    );
  })
]);

celestialData將是日期結果的數組。

如果你願意,你可以為第三部分使用簡潔的箭頭函數:

  ...dates.map(date => axios.get(
    `https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`
  )

旁注:您當前創建dates數組的方式很好,但如果您願意,可以使用Array.from的映射能力:

const dates = Array.from(
  Array(9),
  (_, i) => moment().add(i, "days").format("YYYY-MM-DD")
);

由於Seblor尚未將其發布為答案,因此這是他們的方法(這對我來說似乎更好,因為它避免了分散數組只是為了在解構中使用 rest 元素再次將其收集起來):

const [cityName, weatherData, celestialData] = await Promise.all([
  axios.get(
    `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${myKey}`
  ),
  axios.get(
    `https://api.darksky.net/forecast/${myKey}/${latitude},${longitude}`
  ),
  Promise.all(dates.map(date => {
    return axios.get(
      `https://api.ipgeolocation.io/astronomy?apiKey=${myKey}&lat=${latitude}&long=${longitude}&date=${date}`
    );
  }))
]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM