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

Add Sema.run utility for easy task processing #43

Open
olee opened this issue May 20, 2021 · 0 comments
Open

Add Sema.run utility for easy task processing #43

olee opened this issue May 20, 2021 · 0 comments

Comments

@olee
Copy link

olee commented May 20, 2021

I think adding the following utility function might simplify working with semaphores a lot

export class Sema {
    public runTask<T>(task: (token?: any) => Promise<T>): Promise<T> {
        return this.acquire().then(token =>
            Promise.resolve(token)
                .then(task)
                .finally(() => sem.release(token))
        );
    }
}

It would allow to simply and safely queue tasks for processing while making sure that acquired tokens are never lost:

const sem = new Sema(3);

// Run many task in parallel limited by sem
for (let i = 0; i < 100; i++) {
    sem.runTask(async () => {
        // do some stuff
    });
}

// Alternatively use Promise.all and map
await Promise.all(items.map(item => sem.runTask(() => processItem(item))))
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