LoginSignup
2
0

スリープを挟みながらaxiosを連続で呼び出す

Last updated at Posted at 2023-05-19

初めに

フロントエンドを行っていると、時々以下のようなAPIに出会うことがある

  1. 全従業員の従業員番号を取得する用のWebAPIをコールする
  2. 従業員の詳細データを取得するWebAPIを従業員番号を引数にコールする

このとき詳細データを取得する間隔をサーバー側が規制している場合に、どうやってJavascriptで実装するかを備忘録として書いておく。

eslintの設定によってはloop内でawaitが使えない場合があるのでその時に使える書き方。
ただしeslintが緩いならloop内awaitのほうがスッキリする。

結論

以下の実装でスリープを挟みながらaxiosをコールできる。

    const result = await axios.get('/employees').then((res1) => {
        const employeeIds = res1.data;
        const sleepInterval = 50; // ms単位
        const sleepTimes = [...Array(employeeIds.length).keys()].map((_, i) => i * sleepInterval);
        return Promise.allSettled(sleepTimes
            .map((sleepTime, i) => new Promise(s => setTimeout(s, sleepTime))
                .then(() => axios.get('/employ_detail', {id: employeeIds[i]))));
    });

以上です。

2
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
2
0