I have two promises from two different API calls in my VUE JS app, I was thinking maybe both could be combined using a promise.all()
approach? If so how could I do this?
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;
});
}
In addition to existing answers, this is when async..await
becomes useful, since it's already used in other functions. The array that Promise.all
resolves to can be destructured:
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;
}