【问题标题】:Is there some way to make recursive fetch requests?有没有办法进行递归获取请求?
【发布时间】:2017-09-25 15:35:38
【问题描述】:

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

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}`);
    });

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

【问题讨论】:

  • 当然有。这只是一个承诺,并且可以链接和嵌套。请向我们展示您的尝试代码。
  • data = json; 是 what won't work

标签: javascript node.js express ecmascript-6 fetch


【解决方案1】:

您可以通过将您对 fetch 的调用包装在一个命名函数中来做到这一点,该函数返回由 fetch 创建的承诺。考虑:

function fetchWithRetry(url, retryLimit, retryCount) {
    retryLimit = retryLimit || Number.MAX_VALUE;
    retryCount = Math.max(retryCount || 0, 0);
    return fetch(url).then(function (res) {
        console.log(res.status);
        if (res.status !== 200 && retryCount < retryLimit) {
            console.log("There was an error processing your fetch request. We are trying again.");
            return fetchWithRetry(url, retryLimit, retryCount + 1);
        } else {
            return res.json();
        }
    });
}

fetchWithRetry('someURLWithAJSONfile/file.json', 10).then(function (json) {
    data = json;
}).catch(function (err) {
    console.log(`There was a problem with the fetch operation: ${err.message}`);
});

此代码包装您现有的调用,并利用闭包范围来维护重试限制和计数,这两个都是可选的。然后,您使用 URL 调用 fetchWithRetry 函数,就像您之前调用 fetch 一样。如果您没有通过重试限制,它将无休止地继续。最后的retryCount 变量实际上只用于递归目的,是为了在内部调用。

【讨论】:

    【解决方案2】:

    这里是简单的 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));
    

    【讨论】:

    • 这个解决方案总是在“.then”调用中返回未定义的错误(不管 res.status)。下面使用传统功能(不是胡萝卜)的另一个解决方案可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 2022-10-25
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 2019-07-04
    相关资源
    最近更新 更多