Skip to content

Instantly share code, notes, and snippets.

@georgecrawford
Last active August 29, 2015 14:13
Show Gist options
  • Save georgecrawford/320a7e2215e280452c7e to your computer and use it in GitHub Desktop.
Save georgecrawford/320a7e2215e280452c7e to your computer and use it in GitHub Desktop.
Promise.all ignoring errors
// Reject if every promise fails, otherwise resolve
// with the values which resolved, ignoring errors.
// Inspired by https://github.com/slightlyoff/ServiceWorker/issues/359
function allThatResolve(promises) {
var results = [],
seen = 0,
length = promises.length;
function done(resolve, reject) {
seen++;
if (seen === length) {
if (results.length) {
resolve(results);
} else {
reject('all failed');
}
}
}
return new Promise(function(resolve, reject) {
promises.reduce(function(chain, promise, index, array) {
// Cast value to Promise
promise = Promise.resolve(promise);
promise.then(function(result) {
results.push(result);
done(resolve, reject);
})
.catch(function(error) {
console.error('Ignoring error:', error);
done(resolve, reject);
});
// Build a chain of promises, where each catches from the previous
return chain.catch(function() {
return promise;
});
}, Promise.reject());
});
}
function timeout(val) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
val ? resolve(val) :reject('timeout');
});
});
}
// => PASS: [1, "hello", true]
allThatResolve([timeout(1), timeout('hello'), timeout(true)])
.then(function(results) {
console.log('PASS:', results);
})
.catch(function(error) {
console.log('FAIL:', error);
})
// => PASS: [1, "hello"]
allThatResolve([timeout(1), timeout('hello'), timeout()])
.then(function(results) {
console.log('PASS:', results);
})
.catch(function(error) {
console.log('FAIL:', error);
})
// => FAIL: all failed
allThatResolve([timeout(), timeout(), timeout()])
.then(function(results) {
console.log('PASS:', results);
})
.catch(function(error) {
console.log('FAIL:', error);
})
@georgecrawford
Copy link
Author

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