Skip to content

leetcode 题库

https://github.com/sl1673495/leetcode-javascript/issues

请求并发控制

ts
/**
 * 请求并发控制
 * @template P 请求参数
 * @template R 响应类型
 * @param request 请求函数
 * @param maxNum 最大并发数
 */
function withMaxConcurrency<P extends any[], R>(request: (...args: P) => Promise<R>, maxNum = 5) {
    const queue = new Map<() => Promise<void>, Promise<void> | null>();
    /**用未发送的请求替代已完成的请求 */
    function replace(oldSend: () => Promise<void>) {
        queue.delete(oldSend);
        for (const [send, promise] of queue) {
            if (promise === null) {
                queue.set(send, send());
                break;
            }
        }
    }
    return function (...args: P) {
        const { promise, resolve, reject } = Promise.withResolvers<R>();
        const sendRequest = () =>
            request(...args)
                .then(resolve, reject)
                .finally(() => replace(sendRequest));
        queue.set(sendRequest, queue.size < maxNum ? sendRequest() : null);
        return promise;
    };
}