JavaScript is required
Blog About

实现对promise时间限制的包装方法

2024/06/12
2 mins read
See this issue
# Javascript
Back

实现一个函数 传入promise和delay,当超过delay,promise还没执行完就将promise置为reject

群里看见的问题,感觉思路还是比较简单的,包装器内置一个倒计时promise,如果是传入的promise先resolve, 就是包装器resolve, 如果是计时器先resolve, 那就说明传入的promise超时了,对其reject

function limitTimePromise(promise, delay) {
  const MARK = Symbol("LIMIT_MARK");
  const innerPromise = new Promise((resolve, reject) =>
    setTimeout(resolve, delay, MARK),
  );

  return Promise.any([innerPromise, promise]).then((values) => {
    if (values === MARK) {
      Promise.reject(promise);
      return "this promise has expired";
    }
    Promise.reject(innerPromise);
    return values;
  });
}