Decorate an async function with limited concurrency, which can be used as the decorator in the future.
$ npm install p-concurrency --save
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)
})
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)
})
class Foo {
constructor () {
this.bar = concurrency(1)(this.bar)
}
async bar (n) {
return await remoteGetSomething(n)
}
}
Or (recommended)
class Foo {
async bar (n) {
return await remoteGetSomething(n)
}
}
const {prototype} = Foo
prototype.bar = concurrency(1)(prototype.bar)
Which is equivalent to:
concurrency({
concurrency: max
})
- options
- concurrency
number
max concurrency - promise
Function (handler: Function)
- when?
Function (): bool
- global?
boolean = false
use global concurrency limiter. Iftrue
, all instances of a class will share a same concurrency queue - key
string | Symbol
the key to save the queue
- concurrency
MIT