LoginSignup
18
15

More than 5 years have passed since last update.

fetchを指定回数リトライさせる書き方

Last updated at Posted at 2019-02-23

JavaScriptのfetchをリトライさせたくて調べて見つけた書き方。

書き方

参考にしたサイト、素晴らしい🙏
ES7のを参考にしたけど、他バージョンの書き方も載っている。
Javascript fetch, retry upon failure

const fetch_retry = async (url, options, n) => {
  try {
    return await fetch(url, options);
  } catch (err) {
    if (n === 1) throw err;
    return await fetch_retry(url, options, n - 1);
  }
};

なるほど。エラーの場合は再帰的にfetch_retryを呼び出すのか。ES7なので、asyncawaitを使っているから、綺麗に書けている。久々にJavaScriptで感心してしまった。

試してみる

1回のリトライごとに1秒のsleepを入れて、実際にリトライが可能かやってみた。ちなみにsleepは下記を参考にした。JavaScriptで簡単にsleepっぽい事ができるようになったのは、すごく嬉しい。
ES2017のasync/awaitを使って「同期的sleep処理」をワンライナーで書く

const fetch = require("node-fetch");

const fetch_retry = async (url, options, n) => {
  try {
    console.log("count=", n);
    return await fetch(url, options);
  } catch (err) {
    await new Promise(r => setTimeout(r, 1000));
    if (n === 1) throw err;
    return await fetch_retry(url, options, n - 1);
  }
};

fetch_retry("http://localhost:8080/hoge", {}, 10)
  .then(res => {
    console.log("Success:", res.status);
  })
  .catch(err => {
    console.log("Error:", err.message);
  });

何回かのリトライの後、成功した場合はこんな感じ。

$ node main.js  
count= 10       
count= 9        
count= 8        
count= 7        
count= 6        
count= 5        
count= 4        
Success: 200    

失敗したときはこんな感じ。

$ node main.js                                                                                  
count= 10                                                                                       
count= 9                                                                                        
count= 8                                                                                        
count= 7                                                                                        
count= 6                                                                                        
count= 5                                                                                        
count= 4                                                                                        
count= 3                                                                                        
count= 2                                                                                        
count= 1                                                                                        
Error: request to http://localhost:8080/hoge failed, reason: connect ECONNREFUSED 127.0.0.1:8080
18
15
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
18
15