手写 Promise 三次重试

手写 Promise 三次重试

代码

function retry(fn, delay, times = 0) {
  if (times >= 3) {
    throw 'timeout error';
  }

  const timeout = new Promise((resolve, reject) => {
    setTimeout(() => {
      reject();
    }, delay);
  })

  return new Promise((resolve, reject) => {
    Promise.race([fn(), timeout]).then((res) => {
      resolve(res);
    }).catch(() => {
      return retry(fn, delay, times + 1);
    }).catch((err) => {
      reject(err);
    })
  })
}

const fn = () => {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, 1000);
  });
}

retry(fn, 500).then(() => {
  console.log('success')
}).catch(err => {
  console.log('error:', err)
})