AbortController.abort()

Aborts an incomplete Web request. This can abort the FETCH request, any consumer and stream that responds to the Body

Promise.race()

The race function returns a Promise that will be completed in the same way as the first Promise passed. It may be a high degree of completion or rejection, depending on which of the two is the first. If the passed iteration is empty, the returned promise will wait forever. If the iteration contains one or more non-promise values and/or resolved/rejected promises, promise.race resolves to the first value found in the iteration.

Returns the first completed Promise


/** * Implement fetch's timeout function *@param {object} fecthPromise fecth
 * @param {Number} Timeout Timeout setting, default 5000ms * */
let controller = new AbortController();
export function fetch_timeout(fecthPromise, timeout = 6000) {
  let abort: any = null;
  let abortPromise = new Promise((resolve, reject) = > {
    abort = () = > {
      return reject({
        code: 504.message: 'Request timed out! '}); }; });// The fastest result promise is the result
  let resultPromise = Promise.race([fecthPromise, abortPromise]);
  setTimeout(() = > {
    abort();
    controller.abort();
  }, timeout);

  return resultPromise.then((res) = > {
    clearTimeout(timeout);
    return res;
  });
}

Copy the code