我有一个fetch-api POST要求:
fetch(url, {
  method: 'POST',
  body: formData,
  credentials: 'include'
})
我想知道默认的超时时间是多少?以及如何将其设置为3秒或不确定的秒之类的特定值?
Answers:
如注释中所指出的,即使在解决了诺言之后,原始答案中的代码仍继续运行计时器。
下面的代码解决了该问题。
function timeout(ms, promise) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      reject(new Error('TIMEOUT'))
    }, ms)
    promise
      .then(value => {
        clearTimeout(timer)
        resolve(value)
      })
      .catch(reason => {
        clearTimeout(timer)
        reject(reason)
      })
  })
}
它没有指定的默认值。该规范根本没有讨论超时。
通常,您可以为承诺实现自己的超时包装器:
// Rough implementation. Untested.
function timeout(ms, promise) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      reject(new Error("timeout"))
    }, ms)
    promise.then(resolve, reject)
  })
}
timeout(1000, fetch('/hello')).then(function(response) {
  // process response
}).catch(function(error) {
  // might be a timeout error
})
如https://github.com/github/fetch/issues/175中所述 (https://github.com/mislav)
.reject()已解决的Promise不会执行任何操作。
                    我真的很喜欢这个干净的方法要点使用Promise.race
fetchWithTimeout.js
export default function (url, options, timeout = 7000) {
    return Promise.race([
        fetch(url, options),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('timeout')), timeout)
        )
    ]);
}
main.js
import fetch from './fetchWithTimeout'
// call as usual or with timeout as 3rd argument
fetch('http://google.com', options, 5000) // throw after max 5 seconds timeout error
.then((result) => {
    // handle result
})
.catch((e) => {
    // handle errors and timeout error
})
fetch发生错误,这将导致“未处理的拒绝” 。这可以通过处理()故障并在尚未发生超时的情况下重新抛出来解决。.catchfetch
                    使用promise race解决方案将使请求挂起,并且仍在后台消耗带宽,并降低仍在处理中的最大并发请求数。
而是使用AbortController实际中止请求,这是一个示例
const controller = new AbortController()
// 5 second timeout:
const timeoutId = setTimeout(() => controller.abort(), 5000)
fetch(url, { signal: controller.signal }).then(response => {
  // completed request before timeout fired
  // If you only wanted to timeout the request, not the response, add:
  // clearTimeout(timeoutId)
})
AbortController也可以用于其他事物,不仅可以获取,还可以用于可读/可写流。更多的新功能(特别是基于承诺的功能)将越来越多地使用此功能。NodeJS还已经在其流/文件系统中实现了AbortController。我知道网络蓝牙也在研究它
在Endless的出色答案的基础上,我创建了一个有用的实用程序功能。
const fetchTimeout = (url, ms, { signal, ...options } = {}) => {
    const controller = new AbortController();
    const promise = fetch(url, { signal: controller.signal, ...options });
    if (signal) signal.addEventListener("abort", () => controller.abort());
    const timeout = setTimeout(() => controller.abort(), ms);
    return promise.finally(() => clearTimeout(timeout));
};
const controller = new AbortController();
document.querySelector("button.cancel").addEventListener("click", () => controller.abort());
fetchTimeout("example.json", 5000, { signal: controller.signal })
    .then(response => response.json())
    .then(console.log)
    .catch(error => {
        if (error.name === "AbortError") {
            // fetch aborted either due to timeout or due to user clicking the cancel button
        } else {
            // network error or json parsing error
        }
    });
希望能有所帮助。
提取API中尚无超时支持。但是可以通过将其包装在承诺中来实现。
例如
  function fetchWrapper(url, options, timeout) {
    return new Promise((resolve, reject) => {
      fetch(url, options).then(resolve, reject);
      if (timeout) {
        const e = new Error("Connection timed out");
        setTimeout(reject, timeout, e);
      }
    });
  }
编辑:提取请求仍将在后台运行,并且很可能会在控制台中记录一个错误。
确实,这种Promise.race方法更好。
请参阅此链接以获取参考Promise.race()
竞赛意味着所有Promise都将同时运行,并且一旦其中一个允诺返回值,竞赛就会停止。因此,将仅返回一个值。如果获取超时,您还可以传递一个函数来调用。
fetchWithTimeout(url, {
  method: 'POST',
  body: formData,
  credentials: 'include',
}, 5000, () => { /* do stuff here */ });
如果这引起了您的兴趣,则可能的实现方式是:
function fetchWithTimeout(url, options, delay, onTimeout) {
  const timer = new Promise((resolve) => {
    setTimeout(resolve, delay, {
      timeout: true,
    });
  });
  return Promise.race([
    fetch(url, options),
    timer
  ]).then(response => {
    if (response.timeout) {
      onTimeout();
    }
    return response;
  });
}
您可以创建一个超时承诺包装器
function timeoutPromise(timeout, err, promise) {
  return new Promise(function(resolve,reject) {
    promise.then(resolve,reject);
    setTimeout(reject.bind(null,err), timeout);
  });
}
然后,您可以兑现任何承诺
timeoutPromise(100, new Error('Timed Out!'), fetch(...))
  .then(...)
  .catch(...)  
它实际上不会取消基础连接,但可以使Promise超时。
参考
  fetchTimeout (url,options,timeout=3000) {
    return new Promise( (resolve, reject) => {
      fetch(url, options)
      .then(resolve,reject)
      setTimeout(reject,timeout);
    })
  }
使用c-promise2 lib可以取消带有超时的获取,可能看起来像这样(Live jsfiddle演示):
import CPromise from "c-promise2"; // npm package
function fetchWithTimeout(url, {timeout, ...fetchOptions}= {}) {
    return new CPromise((resolve, reject, {signal}) => {
        fetch(url, {...fetchOptions, signal}).then(resolve, reject)
    }, timeout)
}
        
const chain = fetchWithTimeout("https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=10s", {timeout: 5000})
    .then(request=> console.log('done'));
    
// chain.cancel(); - to abort the request before the timeout
将此代码作为npm包cp-fetch