使用 fetch 封装异步请求

502 阅读1分钟

使用 fetch 封装异步请求

实现一个 http 方法发送异步请求,具体要求如下:

  • 使用 fetch api 发送异步请求
  • 返回值为 promise
  • 支持超时取消 promise
// http 方法简易实现

const defaultTimeout = 20000

const http = (url, config = {}) => {
    const { timeout = defaultTimeout } = config
    return new Promise(async (resolve, reject) => {
        try {
            const controller = new AbortController()
            const signal = controller.signal
            const timer = setTimeout(() => {
                // 当 abort() 被调用,fetch() promise 将会抛出一个 AbortError
                controller.abort()
            }, timeout)
            
            const res = await fetch(url, { ...config, signal })
            
            clearTimeout(timer)
            // 响应的 HTTP 状态码不在 200 - 299 的范围内
            // Promise 状态标记依然标记为 resolve,此时 resolve 返回值的 ok 属性为 false
            if (!res.ok) throw new Error('request error')
            
            resolve(res.json())
        } catch (err) {
            reject(err)
        }
    })
}

http('https://developer.mozilla.org')

fetch api 的优点

  • 可跨平台使用,Node、浏览器中均支持
  • 使用 Promise 的方式,避免嵌套地狱
  • 通过数据流处理数据,可以分块读取,有利于提高网站性能表现
  • 采用模块化设计,API 分散在多个对象上(Response 对象、Request 对象、Headers 对象)

相关链接