Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/kaelzhang/p-concurrency

Decorate async functions with limited concurrency, which can be used as decorator in the future.
https://github.com/kaelzhang/p-concurrency

async concurrency javascript nodejs promise

Last synced: 20 days ago
JSON representation

Decorate async functions with limited concurrency, which can be used as decorator in the future.

Awesome Lists containing this project

README

        

[![Build Status](https://travis-ci.org/kaelzhang/p-concurrency.svg?branch=master)](https://travis-ci.org/kaelzhang/p-concurrency)

# p-concurrency

Decorate an async function with limited concurrency, which can be used as the decorator in the future.

## Install

```sh
$ npm install p-concurrency --save
```

## Usage

```js
const {concurrency} = require('p-concurrency')

// used as a decorator
@concurrency(1)
async function get (n) {
return await remoteGetSomething(n)
}

// or
get = concurrency(1)(get)

// only one promise is run at once
Promise.all([
get(),
get(),
get()
]).then(result => {
console.log(result)
})
```

### It can also be used with classes

```js
class Foo {
@concurrency(1)
async bar (n) {
return await remoteGetSomething(n)
}
}

const foo = new Foo

// only one promise is run at once
Promise.all([
foo.bar(),
foo.bar(),
foo.bar()
]).then(result => {
console.log(result)
})
```

### Use as no decorators with classes

```js
class Foo {
constructor () {
this.bar = concurrency(1)(this.bar)
}

async bar (n) {
return await remoteGetSomething(n)
}
}
```

Or (recommended)

```js
class Foo {
async bar (n) {
return await remoteGetSomething(n)
}
}

const {prototype} = Foo
prototype.bar = concurrency(1)(prototype.bar)
```

## concurrency(max)

Which is equivalent to:

```js
concurrency({
concurrency: max
})
```

## concurrency(options)

- **options**
- **concurrency** `number` max concurrency
- **promise** `Function (handler: Function)`
- **when?** `Function (): bool`
- **global?** `boolean = false` use global concurrency limiter. If `true`, all instances of a class will share a same concurrency queue
- **key** `string | Symbol` the key to save the queue

## License

MIT