javascript 处理并发
//并发请求处理
export const limitLoad = (urls, handler, limit) => {
    let sequence = [].concat(urls);
    let promises = sequence.splice(0, limit).map((url, index) => {
        return handler(url).then(() => {
            return index;
        });
    });
    return sequence.reduce((pCollect, url) => {
        return pCollect
            .then(() => {
                return Promise.race(promises);
            })
            .then(fastestIndex => {
                promises[fastestIndex] = handler(url).then(
                    () => {
                        return fastestIndex;
                    }
                );
            })
            .catch(err => {
                console.error(err);
            });
    }, Promise.resolve())
    .then(() => {
        return Promise.all(promises);
    });
}


2、只使用promise.all

Promise.all: 方法返回一个 Promise 实例,此实例在 iterable 参数内所有的 promise 都“完成(resolved)”或参数中不包含 promise 时回调完成(resolve);如果参数中  promise 有一个失败(rejected),此实例回调失败(reject),失败的原因是第一个失败 promise 的结果。

const limitLoad = (urls, handler, limit) => {
    let sequence = [].concat(urls);

    const recurision = data => {
        return handler(sequence.shift()).then(() => {
            if(data.length){
                return recurision(data);
            }
            return 'done'
        })
    }


    const asyncList = [];
    while(limit--){
        asyncList.push(recurision(sequence));
    }

    return Promise.all(asyncList).then(res => {
        console.log('done');
    });
}
确认 取消
1条评论