-
Notifications
You must be signed in to change notification settings - Fork 34
Open
Description
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))))Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels