获取API请求超时? [英] Fetch API request timeout?

查看:121
本文介绍了获取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?

推荐答案

它没有指定的默认值; 规范根本不讨论超时。

It doesn't have a specified default; the specification doesn't discuss timeouts at all.

您可以为promises实现自己的超时包装器:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆