JS:处理多个顺序失败的异步请求 [英] JS: handle multiple sequential failed async requests

查看:34
本文介绍了JS:处理多个顺序失败的异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用承诺(带有等待).我有一个必须等​​待异步请求的异步函数:例如一个 http 请求.HTTP 请求可能会失败(超时或其他动机),但我需要回忆它直到成功或直到完成最大尝试次数(假设为 n 次尝试),然后继续执行该函数.我无法找到一种干净且组织良好的方式来做到这一点.下面是伪代码:

I'm using promises (with await). I have an async function that has to await an async request: an http request for example. The HTTP request can fail (timeout or other motivations) but I need to recall it until success or until a max number of attempts are done (let's say n attempts) and then continue the execution of the function. I wasn't able to find a clean and well organized way to do this. Below a pseudocode:

async function func(){
  //DO something before HTTP request
  try{
    let res = await http_request();
  } catch(e){
    //http request failed
    //WHAT TO DO HERE TO CALL AGAIN THE HTTP REQUEST until success??
    //or until max attempts == n?
  }
  //DO other stuff only after the http request succeeded
  return;
}

这个想法是在最后返回一个承诺,如果 http 请求和其余代码成功或拒绝,如果 http 请求尝试失败 n 次或其他错误.

the idea would be to return at the end a promise which resolves if the http requests and the rest of the code succeeded or rejects if the http request attempts failed n times or other errors.

PS:http 请求是一个示例,但 http_request() 可以替换为任何其他异步函数.

PS: the http request is an example but http_request() can be substituted with any other async function.

推荐答案

你可以再次调用你的函数来重试,你可以传递一个重试计数器.您可能还应该在重试之前插入一个短暂的延迟,以避免破坏繁忙的服务器.

You can just call your function again to retry and you can pass it a retry counter. You should also probably insert a short delay before retrying to avoid hammering a busy server.

function delay(t, v) {
   return new Promise(resolve => {
       setTimeout(resolve.bind(null, v), t);
   });
}

const kMaxAttempts = 10;
const kDelayBeforeRetry = 500;

async function func(cntr = 0){
  //DO something before HTTP request
  ++cntr;
  try{
    let res = await http_request();
    //DO other stuff only after the http request succeeded
    return finalValue;
  } catch(e){
    // test to see if max retries have been exceeded
    // also examine e to see if the error is retryable
    if (cntr > kMaxAttempts || e is not a retryable error) {
        throw e;
    }
    // retry after a short delay
    return delay(kDelayBeforeRetry, cntr).then(func);

  }
}

这篇关于JS:处理多个顺序失败的异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆