控制并发数量

async function limitConcurrency(asyncFunctions, maxConcurrency = 5) {
    const results = [];
    const executing = [];
    for (const asyncFunction of asyncFunctions) {
        const promise = asyncFunction().then(result => {
            results.push(result);
            executing.splice(executing.indexOf(promise), 1);
            return result;
        });
        executing.push(promise);
        if (executing.length >= maxConcurrency) {
            await Promise.race(executing);
        }
    }
    return Promise.all(results);
}

// 假设我们有以下异步函数列表
const asyncFunctions = Array.from({length: 20}, (_, i) => () => 
    new Promise(resolve => setTimeout(() => resolve(i), 1000))
);

// 我们希望限制并发数为5
limitConcurrency(asyncFunctions, 5).then(results => {
    console.log('所有操作完成', results);
});
  1. 初始化结果数组results和正在执行的操作数组executing
  2. 遍历异步函数列表,对每个函数调用生成一个Promise并将其推入executing数组。
  3. executing中的Promise数量达到maxConcurrency时,使用Promise.race(executing)等待至少一个Promise完成。这会阻塞进一步的迭代,直到至少一个操作完成并从executing数组中移除。
  4. 每当一个Promise完成,它就会从executing数组中移除,允许下一个异步操作开始。
  5. 最后,使用Promise.all(results)确保所有操作都完成后返回所有结果。

问题

await Promise.all(this.skuImageData.map(async (imageInfo): Promise<ProductSkuImageHandle> => {
            const { path, attributeValue } = imageInfo;
            const localPath = await this.imageProcess.getImageAndSaveLocal(path, md5(+new Date()));
        
        }));
        并发情况下 md5 会重复;日期对象可能复用了?