Created
June 23, 2016 18:31
-
-
Save perry-mitchell/dfe8becce634689206725af318b44445 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one!
Usage Example:
Call 2 promises and return in under 2s with any promises which completed: