如何解决第一次抛出后循环异步 API 获取失败
我正在使用 Apollo 的数据源类从 REST-apis 获取数据。 https://www.npmjs.com/package/apollo-datasource-rest
提取工作正常,但有时服务器响应损坏的信息。发生这种情况时,我想重新获取前一个函数,直到它以正确的响应响应。
我尝试基于这篇文章实现递归重新获取https://dev.to/ycmjason/javascript-fetch-retry-upon-failure-3p6g
递归工作正常,但是当发生损坏的响应并且函数抛出以捕获循环时,后面的函数会立即运行,甚至不会尝试重新获取数据。
async fetchFromAPI(options,n=3) {
console.log(`Fetching from address...`)
try{
let response = await this.get(options)
if (response && response.code === 200 && response.response.length === 2) throw 'invalid response'
return Array.isArray(response.response)
? response.response.map(item => item)
: [];
} catch(error){
if (n === 0) throw new Error("Failed to reach server after 3 attempts");
console.log(`Error occurred while trying to reach. Refetching....`)
return await this.fetchFromAPI(options,n-1);
}
}
如前所述,catch 循环后的后面的语句会立即运行,无需连接 API。我应该在代码中更改什么,以便它为 API 异步获取三次直到停止?
我尝试过 for 循环和辅助函数,结果都是一样的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。