Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
// Promises are started in parallel.
// Resolves with the first resolved value in array order.
// If there's no winner, it rejects with last rejection.
Promise.preferred = function (promisesOrdered) {
return new Promise((resolve, reject) => {
var resolvedValues = new WeakMap();
var resolvables = promisesOrdered.slice(); // copy
function onMemberResolved(value, member) {
resolvedValues.set(member, value);
if (member == resolvables[0])
function onMemberRejected(reason, member) {
resolvables.splice(resolvables.indexOf(member), 1);
var firstValue = resolvedValues.get(resolvables[0]);
if (firstValue)
else if (!resolvables.length)
function observeSettled(promise) {
promise.then(v => onMemberResolved(v, promise))
.catch(r => onMemberRejected(r, promise));
Promise.firstInOrder = Promise.preferred;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment