gpt4 book ai didi

javascript - 使用 async/await 和 try/catch 进行分层 api 调用

转载 作者:行者123 更新时间:2023-11-29 10:30:42 25 4
gpt4 key购买 nike

那么 friend !

我需要调用一个 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();
});
};

感谢指导和意见!

最佳答案

避免 Promise constructor antipattern ,并使用参数而不是外部范围变量作为递归计数:

function identityCheck(slug) {
const toTry = [
slug,
`package/${slug}`,
`${slug}-list`
];
async function attempt(tryIndex) {
try {
return await Bundle.sdk.find(toTry[tryIndex]);
} catch (err) {
console.log(`toTry ${toTry[tryIndex]} did not work ========`, slug, err);
if (tryIndex >= toTry.length) {
throw new Error('Everything is broken forever.'));
} else {
return attempt(tryIndex+1);
}
}
}
return attempt(0);
}

关于javascript - 使用 async/await 和 try/catch 进行分层 api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46801690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com