Last active
August 29, 2015 14:13
-
-
Save georgecrawford/320a7e2215e280452c7e to your computer and use it in GitHub Desktop.
Promise.all ignoring errors
This file contains 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
// 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); | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better: https://gist.github.com/jakearchibald/201eb256be3ff6dac1d8