Rain120 / Web-Study

日常学习,工作写的笔记
66 stars 108 forks source link

实现一个并发功能 #31

Open Rain120 opened 2 years ago

Rain120 commented 2 years ago

题目

const timeout = i =>
    new Promise(resolve => {
        console.log(i);
        setTimeout(() => resolve(i), i);
    });

const data = Date.now();
function asyncPool(list, callback, limit) {
  // ...
}

asyncPool([1000, 5000, 3000, 2000], timeout, 2).then(results => {
    console.log(results); // [ 1000, 5000, 3000, 2000 ]
    console.log(Date.now() - data); //6018
});
Rain120 commented 2 years ago
function asyncPool(list, callback, limit) {
    const promises = [];
    const executing = [];
    let i = 0;

    const enqueue = () => {
        if (i === list.length) {
            return Promise.resolve();
        }

        const task = list[i++];

        const p = Promise.resolve().then(() => {
            return callback && callback(task, i);
        });
        promises.push(p);

        const e = p.then(() => {
            const eIndex = executing.indexOf(e);

            if (eIndex > -1) {
                executing.splice(eIndex, 1);
            }
        });
        executing.push(e);

        let r = Promise.resolve();

        if (executing.length >= limit) {
            r = Promise.race(executing);
        }

        return r.then(() => enqueue());
    }

    return enqueue().then(() => Promise.all(promises));
}