【发布时间】:2019-07-20 20:46:00
【问题描述】:
我有一个递归异步函数getResponse(url,attempts = 0),它轮询外部 api 以获取响应,并在达到 X 次重试或服务器错误后解决或退出。
但是,它的内部“时钟”基于重试次数(在允许延迟以避免速率限制之后),但我也希望灵活地设置基于时间的计时器,这将解决函数并结束递归。理想情况下,我希望能够将基于时间的计时器包装在我的递归异步函数周围,就像timed(getResponse(url),3400)
我只设法让基于时间和基于“重试”的计时器一起工作,方法是将两个计时器打包在一个异步函数中,使用局部变量 expired 作为退出标志并在两个函数上设置 Promise.race 条件.
async function timedgetResponse (expiry = 3500,url) {
let expired = false;
async function timeout(expiry){
await new Promise(_=> setTimeout(_,expiry));
expired = true;
return false;
};
async function getResponse(url,attempts = 0){
try {
if(expired){ return false; };
const limit = 10;
if(attempts >= limit){ok: false, e:"MAX_ATTEMPTS"};
const rawRes = await fetch(url,
{
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json'
}
});
if (!rawRes.ok) { throw (Error('SERVER_ERROR')); };
const res = await rawRes.json();
if(!res || res.status === 0){ throw (Error(res.request)); };
return {ok: true, res: res.request};
} catch(e){
const err = e.message;
if(err === "RESPONSE_NOT_READY"){
await new Promise(_ => setTimeout(_, 333));
attempts +=1;
return getResponse(url,attempts);
} else
if(err === "SERVER_ERROR_ON_RESOLVER"){
await new Promise(_ => setTimeout(_, 10000));
attempts +=1;
return getResponse(url,attempts);
} else {
return {ok: false, e:"MISC_ERROR"};
};
};
};
const awaited = await Promise.race([
getResponse(url),
timeout(expiry)
]);
return awaited;
};
我觉得这不是正确的做法,并希望对timed(getResponse(url),3400) 解决方案提供任何帮助。
【问题讨论】:
-
是的,如果您想在计时器到期时停止重试,那么您需要这些功能一起工作 - 没有办法解决这个问题。您只能通过在重试功能中明确支持取消来分离功能。
-
您是否还在寻找取消的方法?第一次阅读您的问题时并不清楚,但根据 Bergi 的回答,我觉得这是您正在寻找的东西。
标签: javascript promise timeout cancellation retry-logic