在我的 VUE JS 应用程序中,我有来自两个不同 API 调用的两个 promise ,我在想也许可以使用 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);
}
}
应用程序.vue
loadWeather(lat, lon) {
API.getAddress(lat, lon).then(result => {
this.address = result.name;
});
API.getForecast(lat, lon).then(result => {
this.forecast = result;
});
}
最佳答案
除了现有的答案,这是 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;
}
关于javascript - 使用 promise.all 组合两个 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61295652/