【发布时间】:2018-03-29 19:50:27
【问题描述】:
朋友们!
我需要调用一个 api;如果失败,我需要使用不同的参数调用相同的 api;如果再次失败,我需要使用第三个不同的参数调用相同的 api;如果在那之后它最终失败了,那就是一个实际的错误,并且可以解决。
我能想到的唯一方法是使用嵌套的 try/catch 语句,ala:
const identityCheck = async (slug) => {
let res;
try {
res = await Bundle.sdk.find(slug);
} catch (err) {
console.log('Fragment didn\'t work ========', slug, err);
try {
res = await Bundle.sdk.find(`package/${slug}`);
} catch (e) {
console.log('Fragment didn\'t work package ========', e);
try {
res = await Bundle.sdk.find(`${slug}-list`);
} catch (error) {
console.log('None of the fragments worked================.', error);
}
}
}
return logResponse(res);
};
identityCheck('fashion');
但似乎必须有另一种更简单的方法来做到这一点。我尝试归结为一个重试函数,但这最终会导致更多的代码和不太清晰的方式:
const identityCheck = (slug) => {
const toTry = [
slug,
`package/${slug}`,
`${slug}-list`
];
return new Promise((resolve, reject) => {
let res;
let tryValIndex = 0;
const attempt = async () => {
try {
res = await Bundle.sdk.find(toTry[tryValIndex]);
return resolve(logResponse(res));
} catch (err) {
console.log(`toTry ${toTry[tryValIndex]} did not work ========`, slug, err);
if (tryValIndex >= toTry.length) {
return reject(new Error('Everything is broken forever.'));
}
tryValIndex++;
attempt();
}
};
attempt();
});
};
感谢您的指导和意见!
【问题讨论】:
标签: javascript async-await try-catch es6-promise