Skip to content

Instantly share code, notes, and snippets.

@jkjustjoshing
Last active July 19, 2017 10:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jkjustjoshing/de488c63074370e28169 to your computer and use it in GitHub Desktop.
Save jkjustjoshing/de488c63074370e28169 to your computer and use it in GitHub Desktop.
Promise.any() – A Missing Use Case
Promise.any = function(arrayOfPromises) {
// For each promise that resolves or rejects,
// make them all resolve.
// Record which ones did resolve or reject
var resolvingPromises = arrayOfPromises.map(function(promise) {
return promise.then(function(result) {
return {
resolve: true,
result: result
};
}, function(error) {
return {
resolve: false,
result: error
};
});
});
return Promise.all(resolvingPromises).then(function(results) {
// Count how many passed/failed
var passed = [], failed = [], allFailed = true;
results.forEach(function(result) {
if(result.resolve) {
allFailed = false;
}
passed.push(result.resolve ? result.result : null);
failed.push(result.resolve ? null : result.result);
});
if(allFailed) {
throw failed;
} else {
return passed;
}
});
};
Promise.any = function(arrayOfPromises) {
if(!arrayOfPromises || !(arrayOfPromises instanceof Array)) {
throw new Error('Must pass Promise.any an array');
}
if(arrayOfPromises.length === 0) {
return Promise.resolve([]);
}
// For each promise that resolves or rejects,
// make them all resolve.
// Record which ones did resolve or reject
var resolvingPromises = arrayOfPromises.map(function(promise) {
return promise.then(function(result) {
return {
resolve: true,
result: result
};
}, function(error) {
return {
resolve: false,
result: error
};
});
});
return Promise.all(resolvingPromises).then(function(results) {
// Count how many passed/failed
var passed = [], failed = [], allFailed = true;
results.forEach(function(result) {
if(result.resolve) {
allFailed = false;
}
passed.push(result.resolve ? result.result : null);
failed.push(result.resolve ? null : result.result);
});
if(allFailed) {
throw failed;
} else {
return passed;
}
});
};
Promise.any([
apiRequestPromise1,
apiRequestPromise2,
apiRequestPromise3
]).then(function(result) {
// at least one of the API calls succeeded
// navigate to new state
}, function() {
// none of the API calls succeeded
// don't navigate, show error
})
var dataInPromise = apiCall('http://example.com');
var totallyUseless = $.get('http://example.com', function(data) {
// do something with the data
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment