Skip to content

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

License

Notifications You must be signed in to change notification settings

kaelzhang/p-concurrency

Repository files navigation

Build Status

p-concurrency

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

Install

$ npm install p-concurrency --save

Usage

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

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

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)

concurrency(max)

Which is equivalent to:

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

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published