Last active
July 28, 2017 19:46
-
-
Save jonbern/dc30f2eaf18fc7759d5d467df346e7bb to your computer and use it in GitHub Desktop.
Alternative to Promise.all which will be resolved even when one or more promises are rejected.
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
function promiseOK() { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(); | |
}, 100); | |
}); | |
} | |
function promiseFail() { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
reject(); | |
}, 200); | |
}); | |
} | |
function WaitFor(promises) { | |
return new Promise((resolve, reject) => { | |
let remaining = promises.length; | |
promises.forEach(promise => { | |
promise | |
.then(() => { | |
decrement(); | |
}) | |
.catch(() => { | |
decrement(); | |
}); | |
}); | |
function decrement() { | |
remaining--; | |
if (remaining === 0) { | |
resolve(); | |
} | |
} | |
}); | |
} | |
WaitFor([ | |
promiseOK(), | |
promiseFail().catch(() => { console.log('catch can still be caught')}), | |
promiseOK(), | |
promiseOK()]) | |
.then(() => { | |
console.log('ALL IS DONE'); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment