美文网首页
AbortController取消Fetch请求和XMLHttp

AbortController取消Fetch请求和XMLHttp

作者: JamesSawyer | 来源:发表于2021-07-28 16:54 被阅读0次

    这个是一个实验性接口,注意兼容性。
    使用过 fetch 请求数据时,如果一定时间未请求完成,可以使用 AbsortController 在前端取消该请求。

    function isPrime(number, timeout = 2000) {
      const controller = new AbortController()
      // 调用其 absort 方法取消请求
      setTimeout(() => controller.abort(), timeout)
      // 调用由远程某个接口
      // 注意这里 fetch 传入的options
      fetch(`http://localhost:8081/isprime?number=${number}`, { signal: controller.signal })
        .then(res => res.json())
        .then(console.log)
        .catch(console.error)
    }
    

    还有应用场景是取消下载什么的,可以根据自己的需要使用。

    参考链接:

    相关文章:

    相关文章

      网友评论

          本文标题:AbortController取消Fetch请求和XMLHttp

          本文链接:https://www.haomeiwen.com/subject/vxaypktx.html