已有封装好的api.js
,现在要根据一组参数来使用Promise.allSettled
同时加载不同的接口,试了很多遍要不就是在调用Promise.allSettled
就运行了,要不就是调用报错。
// 旧代码,不方便改动
export function apiShow1(params) {
return axios.get(`fake_api1?id=${params.id}`);
}
export function apiShow1(params) {
return axios.get(`fake_api2?id=${params.id}`);
}
我的尝试
// vue methods
async validateSth() {
const pages = [
{ type: "aa", params: { id: 1 } },
{ type: "bb", params: { id: 2 } },
];
const apiPromises = [];
let isVerified = true;
for (let i = 1; i < pages.length; i += 1) {
apiPromises.push(new Promise((resolve) => {
const page = pages[i];
switch (page.type) {
case "aa": {
return apiShow1(page.params)
.then((res) => { /* doSth1 */ }
.catch(() => (isVerified = false));
}
case "bb": {
return apiShow1(page.params)
.then((res) => { /* doSth2 */ }
.catch(() => (isVerified = false));
}
}
})
}
// 注释掉下面的代码依然会运行,我不知道应该怎么改
// await Promise.allSettled(pagePromises);
return isVerified;
}
async onsubmit() {
this.loading = true;
if (await this.validateSth()) {
console.log("submit")
}
this.loading = false;
}