Created
January 25, 2016 18:41
-
-
Save jakubkulhan/90f2f44dd4111a3f1ca0 to your computer and use it in GitHub Desktop.
WaitGroup.js
This file contains 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
class WaitGroup { | |
constructor() { | |
this.pending = 0; | |
this.values = []; | |
this.promise = Promise.resolve(this.values); | |
} | |
add(promise) { | |
if (this.pending <= 0) { | |
this.promise = new Promise((resolve, reject) => { | |
this.resolve = resolve; | |
this.reject = reject; | |
}); | |
} | |
var i = this.pending++; | |
promise.then( | |
(value) => { | |
this.values[i] = value; | |
if (--this.pending <= 0) { | |
this.resolve(this.values); | |
} | |
}, | |
(err) => { | |
this.reject(err); | |
} | |
) | |
} | |
then(onFulfilled, onRejected) { | |
return this.promise.then(onFulfilled, onRejected); | |
} | |
catch(onRejected) { | |
return this.promise.catch(onRejected); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment