Skip to content

Instantly share code, notes, and snippets.

@zignd
Created September 4, 2021 07:07
Show Gist options
  • Select an option

  • Save zignd/35e6c4beceb83accf1d0998e98c9210d to your computer and use it in GitHub Desktop.

Select an option

Save zignd/35e6c4beceb83accf1d0998e98c9210d to your computer and use it in GitHub Desktop.
Golang-like WaitGroup implementation for Node.js
const EventEmitter = require('events')
class WaitGroup {
constructor() {
this.addedCount = 0
this.currentCount = 0
this.emitter = new EventEmitter()
}
add(delta = 1) {
this.currentCount += delta
if (delta > 0) this.addedCount += delta
if (this.currentCount <= 0) this.emitter.emit('done')
}
done() {
this.add(-1)
}
wait() {
return new Promise((resolve) => {
if (this.currentCount <= 0) {
resolve()
return
}
this.emitter.once('done', () => resolve())
})
}
}
module.exports = WaitGroup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment