Skip to content

实现promise超时控制

实现一个promise超时控制函数,接收一个promise实例和一个超时时间,返回一个新的promise实例。如果promise实例在超时时间内没有完成,那么就会拒绝该promise实例,且拒绝原因是一个超时错误。

实现代码展示

1.无请求取消的超时控制

js
const promiseTimeout = (promise, timeout) => {
    let timeoutId = null
    const timeoutError = () => {
        return new Promise((resolve, reject) => {
            timeoutId = setTimeout(() => {
                reject(new Error('Promise timed out ' + timeout + 'ms'))
            }, timeout)
        })
    }
    return Promise.race([promise, timeoutError()]).finally(() => {
        clearTimeout(timeoutId)
    })
}

2.有请求取消的超时控制

js
const promiseTimeout = (promise, timeout, signal) => {
    let timeoutId = null

    const abortHandle = () => {
        clearTimeout(timeoutId)
        signal?.removeEventListener('abort', abortHandle)
    }
    const timeoutError = () => {
        return new Promise((resolve, reject) => {
            timeoutId = setTimeout(() => {
                reject(new Error('Promise timed out ' + timeout + 'ms'))
                signal?.addEventListener('abort', abortHandle)
            }, timeout)
        })
    }
    return Promise.race([promise, timeoutError()]).finally(() => {
        clearTimeout(timeoutId)
    })
}

使用示例:

js
const controller = new AbortController()
const signal = controller.signal
const promise = fetch('https://gitxxxx.com/', { signal })
promiseTimeout(promise, 1000, signal).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})