并发请求

/**
 * Executes an array of asynchronous functions concurrently with a maximum number of parallel executions.
 * @param fnList An array of functions that return a Promise.
 * @param maxNum The maximum number of parallel executions.
 * @returns A Promise that resolves to an array of results or errors from the executed functions.
 */
function curRequest(fnList: (() => Promise<any>)[], maxNum: number) {
    if (!fnList.length) return Promise.resolve([]);

    return new Promise(resolve => {
        let index = 0;
        // 记录已经完成的数量
        let count = 0;
        const result: any[] = [];
        async function _request() {
            const i = index;
            const fn = fnList[index];
            if (!fn) return null;
            index++;
            try {
                const res = await fn();
                result[i] = res;
            } catch (e) {
                result[i] = e;
            } finally {
                count++;
                if (index < fnList.length) {
                    _request();
                }
                if (count === fnList.length) {
                    resolve(result);
                }
            }
        }

        for (let n = 0; n < Math.min(fnList.length, maxNum); n++) {
            _request();
        }
    });
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容