使用promise.all合并两个诺言

问题描述 投票:2回答:4

我在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;
  });
}
javascript vue.js es6-promise
4个回答
2
投票

除了现有答案之外,这是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;
}

1
投票

[首先,如果两个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返回结果数组。如果您认为您向其传递了一组诺言,那么这是有道理的。


1
投票

是,您可以写

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

但是,实际上这似乎没有必要,因为两个函数都已经处理了错误,并且似乎没有理由解释为什么属性分配需要等待bo​​th兑现。


1
投票

是的,您可以使用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;
}
© www.soinside.com 2019 - 2024. All rights reserved.