Skip to content

Instantly share code, notes, and snippets.

@perry-mitchell
Created June 23, 2016 18:31
Show Gist options
  • Save perry-mitchell/dfe8becce634689206725af318b44445 to your computer and use it in GitHub Desktop.
Save perry-mitchell/dfe8becce634689206725af318b44445 to your computer and use it in GitHub Desktop.
function promiseAllTimeout(promises, timeout, resolvePartial=true) {
return new Promise(function(resolve, reject) {
let results = [],
finished = 0,
numPromises = promises.length;
let onFinish = function() {
if (finished < numPromises) {
if (resolvePartial) {
(resolve)(results);
} else {
throw new Error("Not all promises completed within the specified time");
}
} else {
(resolve)(results);
}
onFinish = null;
};
for (let i = 0; i < numPromises; i += 1) {
results[i] = undefined;
promises[i].then(
function(res) {
results[i] = res;
finished += 1;
if (finished === numPromises && onFinish) {
onFinish();
}
},
reject
);
}
setTimeout(function() {
if (onFinish) {
onFinish();
}
}, timeout);
});
}
@cawoodm
Copy link

cawoodm commented Mar 3, 2020

Nice one!

Usage Example:

Call 2 promises and return in under 2s with any promises which completed:

let res = await promiseAllTimeout([myPromise1, myPromise2], 2000, true);
myPromise1Results = res[0]; // May be undefined if >2s
myPromise2Results = res[1]; // May be undefined if >2s

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