获取 API 请求超时? [英] Fetch API request timeout?
本文介绍了获取 API 请求超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 fetch-api
POST
请求:
fetch(url, {
method: 'POST',
body: formData,
credentials: 'include'
})
我想知道这个的默认超时时间是多少?我们如何将其设置为特定值,例如 3 秒或无限秒?
I want to know what is the default timeout for this? and how can we set it to a particular value like 3 seconds or indefinite seconds?
推荐答案
Edit 1
正如评论中所指出的,即使在承诺被解决/拒绝之后,原始答案中的代码也会继续运行计时器.
Edit 1
As pointed out in comments, the code in the original answer keeps running the timer even after the promise is resolved/rejected.
下面的代码解决了这个问题.
The code below fixes that issue.
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)
})
})
}
原答案
它没有指定的默认值;规范根本没有讨论超时.
您可以为承诺实现自己的超时包装器:
You can implement your own timeout wrapper for promises in general:
// 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
这篇关于获取 API 请求超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文