Skip to content

Instantly share code, notes, and snippets.

@jakearchibald
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save jakearchibald/201eb256be3ff6dac1d8 to your computer and use it in GitHub Desktop.

Select an option

Save jakearchibald/201eb256be3ff6dac1d8 to your computer and use it in GitHub Desktop.
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;
});
}
// 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