@murayamaの技術ブログ
const retry = (fn, option = {retryMax: 2, sleep: null}) => {  
  let retryCount = 0;  
  let aborted = false;  

  const run = (resolve, reject) => {  
    const abort = err => {  
      console.log(`retry abort ${err}`);  
      aborted = true;  
      reject(err || new Error('Aborted.'));  
    };  

    const onError = err => {  
      if (!aborted) {  
        if (retryCount < option.retryMax) {  
          retryCount++;  
          runAttempt();  
          return;  
        } else {  
          reject(err);  
        }  
      }  
    };  

    const runAttempt = async () => {  
      if (retryCount > 0 && option.sleep) {  
        await sleep();  
      }  

      fn(abort, retryCount)  
        .then(resolve)  
        .catch(onError);  
    };  

    runAttempt();  
  };  

  const sleep = () => {  
    return new Promise((resolve, reject) => {  
      console.log(`retry sleep ${option.sleep}`);  
      setTimeout(() => resolve(), option.sleep);  
    });  
  };  

  return new Promise(run);  
};  

このログへのコメント

コメントはありません