Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AkyunaAkish/a69663f7d589abc1dc59b1cc6cac4060 to your computer and use it in GitHub Desktop.
Save AkyunaAkish/a69663f7d589abc1dc59b1cc6cac4060 to your computer and use it in GitHub Desktop.
function asyncFunction(bool) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(bool) {
resolve('Promise resolved after .5 of a second');
} else {
reject('Promise rejected after .5 of a second');
}
}, 500);
});
}
// Array of unresolved promises
const promises = [ asyncFunction(true), asyncFunction(false), asyncFunction(true) ];
// Recursive function that will resolve an array of promises and return
// an object will all the resolved and rejected values. { resolves: [], rejects: [] }
function recursivelyGatherResults(promises, resolves = [], rejects = []) {
// Base case to end recursive iterations when promises
if(!promises.length) {
return { resolves, rejects };
} else {
// to keep the function pure, every recursive call
// creates a copy of the promises array before splicing the next promise
const promisesCopy = promises.concat([]);
// this splices the next promise that needs to be resolved or rejected
const nextPromise = promisesCopy.splice(0,1)[0];
// The first return makes sure that a promise is returned to the original function call.
return nextPromise.then((result) => {
// If this promise resolves, push its result into the resolves array
resolves.push(result);
// Then recursively call this function with the newly updated values
// Making sure to return in order to bubble the results up the the
// final return statement
return recursivelyGatherResults(promisesCopy, resolves, rejects);
})
.catch((err) => {
// If this promise rejects, push its result into the rejects array
rejects.push(err);
// Then recursively call this function with the newly updated values
// Making sure to return in order to bubble the results up the the
// final return statement
return recursivelyGatherResults(promisesCopy, resolves, rejects);
});
}
}
// Invoking the recursive function and passing an array
// of unresolved promises
recursivelyGatherResults(promises).then((result) => {
// 'result' is an object of all resolved and rejected values
console.log('Final result: ', result);
// {
// resolves: [ 'Promise resolved after .5 of a second',
// 'Promise resolved after .5 of a second' ],
// rejects: [ 'Promise rejected after .5 of a second' ]
// }
})
.catch((err) => {
// If something is wrong with the function syntax this catch
// will get the error. If a promise rejects however this catch
// will not be invoked.
console.log('Fatal error in recursivelyGatherResults: ', err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment