尝试3. 第一次抽象

node v10.24.1
version: 1.0.0
endpointsharetweet
const results = []; const timeout = i => new Promise(resolve => setTimeout(() => { results.push(i); resolve(); }, i) ).then(() => { return i }); const urls = [100, 500, 300, 200] /** * 并发工具函数 * @param {any[]} queue 待处理队列 * @param {() => Promise<any>} fn 异步函数,返回一个promise * @param {Number} max 并发上限 * @param {() => any} callback 回调 */ function sendRequestIdle (queue, fn = () => Promise.resolve(), max = 1, callback) { const len = queue.length; let idx = 0, cnt = 0; function _request() { while(idx < len && max > 0) { max-- fn(queue[idx++]).finally(() => { max++ cnt++ if(len === cnt) { return callback() } else { _request() } }) } } _request() } sendRequestIdle(urls, timeout, 2, () => {console.log(results)})
Loading…

no comments

    sign in to comment