Rob*_*Rob 4 javascript vue.js es6-promise
我的 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);
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序.vue
loadWeather(lat, lon) {
API.getAddress(lat, lon).then(result => {
this.address = result.name;
});
API.getForecast(lat, lon).then(result => {
this.forecast = result;
});
}
Run Code Online (Sandbox Code Playgroud)
除了现有的答案之外,这就是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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2186 次 |
| 最近记录: |