Created
September 4, 2021 07:07
-
-
Save zignd/35e6c4beceb83accf1d0998e98c9210d to your computer and use it in GitHub Desktop.
Golang-like WaitGroup implementation for Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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