【问题标题】:timer wrapper function for recursive async/await call用于递归异步/等待调用的计时器包装函数
【发布时间】: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


【解决方案1】:

我有一个功能可以满足你的需要。我已根据我对您需求的解释对其进行了更新。这个想法是您将进行轮询,直到某些事情为真,即解决或您超过最大尝试次数。它具有内置的可配置延迟。

这里的想法是您将传入一个包装您的 fetch 调用的函数,该调用最终会解析/拒绝。

setPolling(pollFunc, freq = 1000, maxAttempts = 3)

pollFunc = 不带参数并返回最终解决或拒绝的承诺的函数。

freq = 以毫秒为单位运行 pollFunc 的频率

maxAttempts = 放弃前的最大尝试次数

const setPolling = async (pollFunc, freq = 1000, maxAttempts = 3, _attempts = 1) => {
  const wait = (delay) => new Promise(resolve=>setTimeout(resolve, delay))
  try {
    return await pollFunc()
  } catch (e) {
    if (_attempts < maxAttempts) {
      await wait(freq)
      return await setPolling(pollFunc, freq, maxAttempts, ++_attempts)
    }
    throw (e instanceof Error) ? e : new Error((typeof e !== 'undefined') ? e : 'setPolling maxAttempts exceeded!')
  }
}

async function alwaysFail() {
    throw new Error(`alwaysFail, failed because that's what it does!`)
}

function passAfter(x) {
  let i = 0
  return async ()=> {
    if (i > x) return `passAfter succeeded because i(${i}) > x(${x})`
    throw new Error(`i(${i++}) < x(${x})`)
  }
}

setPolling(alwaysFail)
  .catch((e)=>console.error(`alwaysFail, failed!\n${e.message}\n${e.stack}`))

setPolling(passAfter(5), 500, 10)
  .then((res)=>console.log(`passAfter, succeeded!\n${res}`))
  .catch((e)=>console.error(`passAfter, failed!\n${e.message}\n${e.stack}`))

【讨论】:

  • 这是否满足 OP 对“基于时间的计时器,它将解析函数并结束递归”的愿望?
  • OP 的要求不明确。要求澄清但尚未给出。
  • 很公平。我有自己的解释,如果我有时间会发布答案。
【解决方案2】:

基于您希望在计时器到期时停止重试,您可以使用token 向递归进程传达停止信号。

应该这样做:

const poll = async (work, options, token) => {
    const settings = Object.assign({ 'delay':0, 'attempts':1, 'maxAttempts':3 }, options);

    // Utility function which returns a Promise-wrapped setTimeout
    const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    // Two mechanisms for stopping the recursion.
    // Performing the tests here ensures they are applied before the first work() call.
    // 1. token-borne stop signal 
    if(token.stop) {
        throw new Error('poll(): stopped');
    }
    // 2. max attempts reached
    if (settings.attempts >= settings.maxAttempts) {
        throw new Error('poll(): max attempts reached');
    }

    // Do the work, and recurse on error
    try {
        return await work();
    }
    catch (e) {
        await delay(settings.delay);
        settings.attempts += 1; // Mutate/pass `settings`; the original `options` is not guaranteed to have an `attempts` property.
        return await poll(work, settings, token);
    }
}

调用如下:

// token
const token = {}; // or {'stop':false} if you like

// Time based timer:
setTimeout(() => {
    token.stop = true; // raise the 'stop' flag
}, 60000); // or whatever

let pollPromise = poll(doSomethingAsync, {'delay':1000, 'maxAttempts':100}, token)
.then((res) => console.log(res))
.catch((e) => console.error(e));

注意在设置停止信号时:

  1. 飞行中的工作仍会成功响应。
  2. 将阻止进一步的递归,但不会尝试中止正在进行的工作。

稍加思考,这些行为可能会根据需要而改变。

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 2021-05-12
    • 2015-08-27
    • 2022-01-27
    • 2019-07-04
    • 2021-08-28
    • 2016-02-21
    • 1970-01-01
    • 2016-09-21
    相关资源
    最近更新 更多