有什么方法可以发出递归获取请求吗?

dan*_*sto 2 javascript fetch node.js express ecmascript-6

我希望我的提取请求有某种重试系统,如果它基于响应的 HTTP 代码(例如:不是 200)以某种方式失败。它看起来像这样:

fetch('someURLWithAJSONfile/file.json')
        .then(function (res) {
            console.log(res.status);
            if (res.status !== 200) {
                console.log("There was an error processing your fetch request. We are trying again.");

// Recursive call to same fetch request until succeeds

            } else {
                return res.json();
            }
        }).then(function (json) {
        data = json;
    }).catch(function (err) {
        console.log(`There was a problem with the fetch operation: ${err.message}`);
    });
Run Code Online (Sandbox Code Playgroud)

有没有办法将获取请求放入自定义 Promise 中,并使其在检查其 http 响应状态后调用自身?

dhi*_*ilt 5

这是简单的 ES6 解决方案(因为您正在使用fetch)。该limit选项表示您想尝试您的请求的次数。

var doRecursiveRequest = (url, limit = Number.MAX_VALUE) => 
  fetch(url).then(res => {
    if (res.status !== 200 && --limit) {
      return doRecursiveRequest(url, limit);
    } 
    return res.json();
  });

doRecursiveRequest('someURLWithAJSONfile/file.json', 10)
  .then(data => console.log(data))
  .catch(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)