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

控制并发数 #31

Open
LiZheGuang opened this issue Dec 23, 2023 · 0 comments
Open

控制并发数 #31

LiZheGuang opened this issue Dec 23, 2023 · 0 comments

Comments

@LiZheGuang
Copy link
Owner

async function asyncPool(poolLimit, array, iteratorFn) {
    const result = [];
    const executing = [];

    for (const item of array) {
        const p = Promise.resolve().then(() => iteratorFn(item, array));
        result.push(p);

        if (poolLimit <= array.length) {
            const e = p.then(() => executing.splice(executing.indexOf(e), 1));
            executing.push(e);
            if (executing.length >= poolLimit) {
                await Promise.race(executing);
            }
        }
    }

    return Promise.all(result);
}

// 示例
async function uploadFile(file) {
    // 文件上传逻辑
}

async function limitedFileUpload(files) {
    return asyncPool(3, files, uploadFile);
}


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