Last active
June 15, 2019 06:29
-
-
Save StefanWallin/e42b8d69b9e3a068e0e41ee86c4f9925 to your computer and use it in GitHub Desktop.
anySuccessfulPromise
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
export default class AnySuccessfulPromise { | |
constructor(promises) { | |
this.promises = promises; | |
this.successes = []; | |
this.errors = []; | |
this.thenCallbacks = []; | |
this.catchCallback = () => { | |
console.error("catch not defined"); | |
}; | |
this.finallyCallbacks = []; | |
this.raceActive = true; | |
this.awaitPromises(); | |
} | |
then(callback) { | |
this.thenCallbacks.push(callback); | |
return this; | |
} | |
catch(callback) { | |
this.catchCallback = callback; | |
return this; | |
} | |
finally(callback) { | |
this.finallyCallbacks.push(callback); | |
return this; | |
} | |
awaitPromises() { | |
this.promises.forEach(promise => { | |
promise | |
.then(result => { | |
if (this.thenCallbacks.length == 0) { | |
console.error("then not defined"); | |
return; | |
} | |
if (this.raceActive) { | |
this.thenCallbacks.forEach(thenCallback => thenCallback(result)); | |
} | |
this.successes.push(result); | |
this.raceActive = false; | |
}) | |
.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.catchCallback(this.errors); | |
this.finallyCallbacks.forEach(finallyCallback => | |
finallyCallback(this.successes, this.errors) | |
); | |
} | |
} |
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 testPromiseFunc = (time, bool) => new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (bool) resolve(time); | |
else reject(time); | |
}, time); | |
}); | |
new AnySuccessfulPromise([ | |
testPromiseFunc(500, true), | |
testPromiseFunc(100, false), | |
testPromiseFunc(300, true), | |
]) | |
.then(console.log.bind(this, 'yay :)')) | |
.catch(console.error.bind(this, 'nay :(')) | |
.finally(console.log.bind(this, 'I\'m done with this!')); | |
/* OUTPUTS: | |
* yay :) (300) | |
* I'm done with this! ([300, 500], [100]) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment