Created
October 4, 2018 11:17
-
-
Save StefanWallin/084220b3760b43dc40907ac15451c3b2 to your computer and use it in GitHub Desktop.
A quick implementation of Promise.any that does not modify the Promise prototype
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 AnyPromise { | |
constructor(promises) { | |
this.promises = promises; | |
this.successes = []; | |
this.errors = []; | |
this.thenCallback = () => { console.error('then not defined'); }; | |
this.catchCallback = () => { console.error('catch not defined'); }; | |
this.finallyCallback = () => {}; | |
this.awaitPromises(); | |
} | |
then(callback) { this.thenCallback = callback; return this; } | |
catch(callback) { this.catchCallback = callback; return this; } | |
finally(callback) { this.finallyCallback = callback; return this; } | |
awaitPromises() { | |
this.promises.forEach((promise) => { | |
promise | |
.then(result => this.successes.push(result)) | |
.catch(result => this.errors.push(result)) | |
.finally(() => { | |
const finishedLength = this.successes.length + this.errors.length; | |
if (finishedLength === this.promises.length) { | |
this.executeCallbacks(); | |
} | |
}); | |
}); | |
} | |
executeCallbacks() { | |
if (this.successes.length > 0) { | |
this.thenCallback(this.successes); | |
} else { | |
this.catchCallback(this.errors); | |
} | |
this.finallyCallback(this.successes, this.errors); | |
} | |
} | |
const testPromiseFunc = (time, bool) => new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (bool) resolve(); | |
else reject(); | |
}, time); | |
}); | |
new AnyPromise([ | |
testPromiseFunc(500, true), | |
testPromiseFunc(1700, false), | |
testPromiseFunc(500, true), | |
]) | |
.then(console.log.bind(this, 'yay :)')) | |
.catch(console.error.bind(this, 'nay :(')) | |
.finally(console.log.bind(this, 'I\'m done with this!')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kudos to @johman10 who paired this with me!