ES7 async await函数中如何使用abort控制器设置超时和重试



我正在尝试获取请求,如果请求需要的时间长于指定的超时,那么我正在使用abort控制器中止它,或者如果响应中有错误,如套接字挂起,那么尝试递归地再次获取它。我想重复它,即5次,在最后,如果它失败,然后返回只是错误。但在我的代码第一次尝试后,它立即失败,并显示获取请求中止。这是我的代码。提前谢谢你。

const getData = async () => {
let url = `https://www.example.com`
let options = {
method: 'POST',
agent: proxyagent,
signal: signal,
body: JSON.stringify({
username: 'abc'
})
}
const fetchData = async (retries) => {
try {
let timer = setTimeout(() => controller.abort(), 1000)
let response = await fetch(url, options)
clearTimeout(timer)
if (response.ok) return response.json()
} catch (e) {
console.log(e)
if (retries === 1 || retries < 1) {
return {
message: 'Something went wrong'
}
}
return await fetchData(retries - 1)
}
}
return await fetchData(5)
}

不能重用已终止的信号。您必须为每个fetch

创建一个新目录。
const getData = async () => {
let url = `https://www.example.com`;
let controller;
let options = {
method: 'POST',
agent: proxyagent,
body: JSON.stringify({
username: 'abc'
})
}
const fetchData = async (retries) => {
controller = new AbortController();
const optionsWithSignal = {
...options,
signal: controller.signal
};
try {
let timer = setTimeout(() => controller.abort(), 1000)
let response = await fetch(url, optionsWithSignal)
clearTimeout(timer);
if (response.ok) return response.json()
} catch (e) {
console.log(e)
if (retries === 1 || retries < 1) {
return {
message: 'Something went wrong'
}
}
return await fetchData(retries - 1)
}
}
return await fetchData(5)
}

相关内容

  • 没有找到相关文章

最新更新