我有一个fetch-api POST请求:
fetch(url, {
method: 'POST',
body: formData,
credentials: 'include'
})我想知道这个的默认超时是什么?我们如何将其设置为3秒或不定秒这样的特定值?
发布于 2018-04-16 12:56:31
更新,因为我原来的答案有点过时,我建议使用中止控制器,如在这里实现的:https://stackoverflow.com/a/57888548/1059828,或者看看这个很好的帖子,用fetch:如何取消HTTP fetch()请求?解释中止控制器
过时的原始答案:
我真的很喜欢这个要旨使用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
})发布于 2019-09-11 11:52:13
在无止境的优秀回答的基础上,我创建了一个有用的实用函数。
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
}
});希望这能有所帮助。
发布于 2017-10-26 05:39:27
在fetch 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);
}
});
}https://stackoverflow.com/questions/46946380
复制相似问题