使用 promise.all 组合两个承诺

Combining two promises using promise.all

我的 VUE JS 应用程序中的两个不同 API 调用有两个承诺,我在想也许可以使用 promise.all() 方法将两者结合起来?如果可以,我该怎么做?

API.js

async function getForecast(lat, lon) {
  try {
    const response = await fetch(`${WEATHER_API_URL}&lat=${lat}&lon=${lon}`);
    return await response.json();
  } catch (error) {
    console.log(error);
  }
}

async function getAddress(lat, lon) {
  try {
    const response = await fetch(`${ADDRESS_API_URL}&lat=${lat}&lon=${lon}`);
    return await response.json();
  } catch (error) {
    console.log(error);
  }
}

App.vue

loadWeather(lat, lon) {
  API.getAddress(lat, lon).then(result => {
    this.address = result.name;
  });
  API.getForecast(lat, lon).then(result => {
    this.forecast = result;
  });
}

是的,您可以使用 Promise.all 合并通话。看看下面你会怎么做...

(我正在使用 setTimouts 代替您的提取请求)

const functionA = async () => {
  await new Promise(resolve => {
    setTimeout(() => { resolve(); }, 2000);
  });

  return "A";
};

const functionB = async () => {
  await new Promise(resolve => {
    setTimeout(() => { resolve(); }, 3000);
  });

  return "B";
};

const getResults = async () => {
  const result = await Promise.all([functionA(), functionB()]);
  return result;
};

getResults().then(result => console.log(result));

查看https://codesandbox.io/s/blue-lake-qupp7?file=/src/index.js

为了将此转化为您的示例,我们可以这样做...

// promise
function loadWeather(lat, lon) {
  Promise.all([
    API.getAddress(lat, lon),
    API.getForecast(lat, lon)
  ]).then(([address, forecast]) => {
    this.address = address.name;
    this.forecast = forecast;
  });
}

// or async/await
async function loadWeather(lat, lon) {
  const [address, forecast] = await Promise.all([
    API.getAddress(lat, lon),
    API.getForecast(lat, lon)
  ]);

  this.address = address.name;
  this.forecast = forecast;
}

首先,决定如果两个 API 调用中的任何一个失败,您是否希望承诺失败。 Promise.all 在这种情况下会失败,Promise.allSettled 不会。这取决于您对应用的需求。

要合并,您可以执行以下操作:

loadWeather(lat, lon) {
  Promise.all([
    API.getAddress(lat, lon),
    API.getForecast(lat, lon)
  ]).then(([addressResult, forecastResult]) => {
    this.address = addressResult.name;
    this.forecast = forecastResult;
  });
}

Promise.all returns 结果数组。如果您考虑向它传递一组承诺,这是有道理的。

是的,你可以写

loadWeather(lat, lon) {
  Promise.all([
    API.getAddress(lat, lon),
    API.getForecast(lat, lon),
  ]).then(([addressResult, forecastResult]) => {
    this.address = addressResult.name;
    this.forecast = forecastResult;
  });
}

然而,这似乎真的没有必要,因为两个函数都已经处理了错误,而且 属性 分配似乎没有理由需要等待 both 承诺履行。

除了现有的答案,这也是 async..await 变得有用的时候,因为它已经在其他函数中使用了。 Promise.all解析到的数组可以被解构:

async loadWeather(lat, lon) {
  const [address, forecast] = await Promise.all([
    API.getAddress(lat, lon),
    API.getForecast(lat, lon)
  ]);
  this.address = address.name;
  this.forecast = forecast;
}