-
-
Save jakearchibald/201eb256be3ff6dac1d8 to your computer and use it in GitHub Desktop.
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 promiseSome(promises) { | |
| var fulfills = []; | |
| var rejects = []; | |
| return promises.reduce(function(chain, promise) { | |
| return chain.then(function() { | |
| return promise; | |
| }).then(function(val) { | |
| fulfills.push(val); | |
| }, function(err) { | |
| rejects.push(err); | |
| }); | |
| }, Promise.resolve()).then(function() { | |
| if (!fulfills[0]) throw Error("All failed"); | |
| return fulfills; | |
| }); | |
| } |
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
| // With comments: | |
| function promiseSome(promises) { | |
| // We're going to 'sort' promises into fulfilled & rejected values | |
| var fulfills = []; | |
| var rejects = []; | |
| // Using reduce to create a promise chain | |
| return promises.reduce(function(chain, promise) { | |
| // Wait for the last in the chain | |
| return chain.then(function() { | |
| // Wait for the current in the chain. | |
| // This has a nice side effect that it deals with values | |
| // in `promises` that are simple values rather than promises | |
| return promise; | |
| }).then(function(val) { | |
| // Store the success value | |
| fulfills.push(val); | |
| }, function(err) { | |
| // Store the failure | |
| // This also 'handles' the error in terms of the chain, | |
| // so the chain always fulfills with undefined | |
| rejects.push(err); | |
| }); | |
| }, Promise.resolve()).then(function() { | |
| // Reject only if nothing fulfilled | |
| if (!fulfills[0]) throw Error("All failed"); | |
| return fulfills; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment