/**
 * 并发执行任务
 * @params {Function[]} tasks
 * @params {Number} parallelCount
 */
function paralleTask(tasks, parallelCount = 2) {
    return new Promise((resolve) => {
        if (tasks.length === 0) {
            resolve();
            return;
        }
        // 下一个任务下标
        let nextIndex = 0;
        // 任务完成的数量
        let finishCount = 0;
        function _run() {
            // 运行下一个任务
            const task = tasks[nextIndex];
            nextIndex++;
            task().then(() => {
                // 运行下一个
                if (nextIndex < tasks.length) {
                    _run();
                } else if (finishCount === tasks.length) {
                    // 任务完成
                    resolve();
                }
            });
        }
        for (let i = 0; i < parallelCount && tasks.length; i++) {
            _run();
        }
    });
}

export default paralleTask;

标签: 暂无标签