1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

fetchのリトライ間隔を動的にする書き方

Posted at

概要

TypeScriptで、fetchのリトライをする必要がありました。
ただ、リトライする際の時間を動的にしたかったのですが、あまり参考になる記事がなかったので記事にしてみました。

実装

ポイントとしては、ループする際、配列の時間分スリープするようにしています。


const TIMES = [1, 3, 5, 15, 45];

const sleep = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

const retry = async (func: () => Promise<boolean>) => {
  for (const time of TIMES) {
    const successful = await func().catch(async () => {
      await sleep(time);
      return false;
    });

    if (successful) break;
  }
};

const send = async function (url: string, body: string): Promise<boolean> {
  const response = await fetch(url, {
    method: 'POST',
    body: body
  }).catch((error) => {
    console.error('Failed');
  });

  if (!response) return false;
  if (!response.ok) {
    console.error('Failed');
    return false;
  }
  return true;
};

実際に使用する部分

await retry(() => send(url, body));

まとめ

等間隔のリトライに関しては、そこそこ記事はあったのですが、動的にリトライする記事はなかったので、参考になればと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?