【javascript】如何给fetch请求设置超时时间,以及结合Promise使用的相关用法

前言

javascript中,fetch函数是用来进行网络请求的,但默认情况下它是不支持超时设置的,如果想要支持超时功能,需要借助AbortController类来实现。

超时设置

fetch函数支持接收一个signal信号,当达到超时时间后,我们可以给fetch函数传递一个信号,让它结束当前请求,从而实现请求超时功能。
而传递signal需要用到AbortController类,代码示例:

// 默认超时时间是5秒
function timeoutFetch(timeout = 5000) {
   
  return (url, option = {
    }) => {
   
    const controller = new AbortController()
    option.signal = controller.signal
    // 设置一个定时器,超时后调用abort方法结束当前请求
    const tid = setTimeout(() => {
   
      console.error(`Fetch timeout: ${
     url}`)
      controller.abort()
    }, timeout)
    return fetch(url, option).finally(() => {
   
      clearTimeout(tid) // 得到请求结果后,要清除定时器
    })
  }
}

用法示例:

// 请求超时时间设置为1秒,接口响应时间为2秒
timeoutFetch(1000)('http://localhost/myProjects/PHP/test/test.php?name=promise1&sleep=2&success=1')
  .then(
    // resolve函数
    response => {
   
      console.log('进入resolve逻辑,成功了')
      console.log(response)
    },
    // reject函数
    reason => {
   
      console.log('进入reject逻辑,失败了')
      console.log(reason)
    }
  )

可以看到&#

你可能感兴趣的:(前端,javascript,fetch,promise,超时)