Skip to content

Add Sema.run utility for easy task processing #43

@olee

Description

@olee

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))))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions