Combining two promises using promise.all
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;}
First, decide if you want the promise to fail if any of the two API calls fail. Promise.all
will fail in this case, Promise.allSettled
will not. It depends on what you want for your app.
To combine, you can do the following:
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 an array of results. This makes sense if you consider that you pass it an array of promises.
Yes, you can write
loadWeather(lat, lon) { Promise.all([ API.getAddress(lat, lon), API.getForecast(lat, lon), ]).then(([addressResult, forecastResult]) => { this.address = addressResult.name; this.forecast = forecastResult; });}
However, it doesn't really seem necessary, as both functions handle errors already and there doesn't seem to be a reason why the property assignments would need to wait for both promises to fulfill.