Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

promise并发控制 #7

Open
heyLiup opened this issue Oct 27, 2020 · 0 comments
Open

promise并发控制 #7

heyLiup opened this issue Oct 27, 2020 · 0 comments

Comments

@heyLiup
Copy link
Owner

heyLiup commented Oct 27, 2020

function sleep (timer) {
    if (timer === 1) {
        return new Promise((res, rej) => rej(1));
    }
    return fetch('XXXX', {method: 'post'})
}



function asyncPool(poolLimit, array, iteratorFn) {
    let i = 0;
    const ret = [];
    const executing = [];

    return new Promise(resolve => {
        const enqueue = function () {
            // 所有请求结束
            if (i === array.length) {
                Promise.all(ret).then(data => {
                    return resolve(data);
                });
            } else {
                const item = array[i++];
                const p = iteratorFn(item);
                ret.push(p);

                // promise执行完毕,从executing数组中删除
                const e = p.then(() => {
                    executing.splice(executing.indexOf(e), 1);
                }, () => {

                    //可兼容reject的情况,将resolve的接口返回
                    ret.splice(ret.indexOf(p), 1);
                });

                // 插入executing数字,表示正在执行的promise
                executing.push(e);

                // 使用Promise.rece,每当executing数组中promise数量低于poolLimit,就实例化新的promise并执行
                let r = Promise.resolve();
                if (executing.length >= poolLimit) {
               
                    r = Promise.race(executing);
                }
                r.then(() => enqueue());
            }
        };

        enqueue();
    })
}

asyncPool(3, arr, sleep).then(res => {
    console.log(res);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant