0

如果失败,我如何重试此获取 x 次?

代码基于这篇文章:https ://dmitripavlutin.com/javascript-fetch-async-await/

async function fetchData() {
  const [firstResponse, secondResponse] = await Promise.all([
    fetch(firstUrl),
    fetch(secondUrl),
  ]);

  const first = await firstResponse.json();
  const second = await secondResponse.json();

  return [first, second];
}

fetchData()
  .then(([first, second]) => {
    console.log("success");
  })

  .catch((error) => {
    console.log("error");
  });

4

1 回答 1

0

由于请求是相互独立的,所以我有一个实用函数,它将重试 X 次,然后在Promise.all. 我还有一个用于获取 JSON 的实用程序函数,fetch它处理不检查 HTTP 成功的 API footgun(请参阅我的博客文章)。所以沿着这些思路:

// Fetch JSON
function fetchJSON(...args) {
    const response = await fetch(...args);
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
}

// Fetch JSON with up to `retries` retries
async fetchJSONWithRetry(retries, ...args) {
    while (retries > 0) {
        try {
            const result = await fetchJSON(...args);
            return result;
        } catch (e) {
            if (--retries === 0) {
                throw e;
            }
        }
    }
}

// Your `fetchData`
async function fetchData(retries = 5) {
    const [first, second] = await Promise.all([
        fetchJSONWithRetry(retries, firstUrl),
        fetchJSONWithRetry(retries, secondUrl),
    ]);
  
    return [first, second];
}
于 2021-03-29T12:08:40.193 回答