Skip to content

Instantly share code, notes, and snippets.

@StefanWallin
Created October 4, 2018 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StefanWallin/084220b3760b43dc40907ac15451c3b2 to your computer and use it in GitHub Desktop.
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
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!'));
@StefanWallin
Copy link
Author

Kudos to @johman10 who paired this with me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment