Promise超时情况

export const ERROR_PROMISE_TIMEOUT = 'ERROR_PROMISE_TIMEOUT';

export default function (promise, timeout) {
  let timer = undefined;
  return Promise.race([
    new Promise(function (resolve, reject) {
      timer = setTimeout(() => {
        reject(new Error(ERROR_PROMISE_TIMEOUT));
      }, timeout)
    }),
    promise.then(res => {
      timer && window.clearTimeout(timer);
      return res;
    }).catch(err => {
      timer && window.clearTimeout(timer);
      return Promise.reject(err);
    })
  ])
}

 

posted @ 2018-11-19 16:15  麦君  阅读(994)  评论(0编辑  收藏  举报