Created
February 16, 2022 18:36
-
-
Save adam8810/e5c0dda916a3e920deba5de62c8bb35d to your computer and use it in GitHub Desktop.
Task: Rewrite promise.all demonstrating knowledge of asynchronous behavior.
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
/* Promise.all Implementation | |
Takes an ordered array of functions that return promises. Returns an ordered array | |
of the results of all promises only after all promises have completed. | |
If, at any point, one promise is rejected it will reject with that error. | |
*/ | |
function promiseAll (promises) { | |
return new Promise(async (resolve, reject) => { | |
const indexedPromises = promises.reduce((ps, p, idx) => ({ ...ps, [idx]: p}), {}); | |
const completedPromises = {}; | |
// We loop through each promise awaiting the result | |
Object.entries(indexedPromises).forEach(async ([idx, promise]) => { | |
try { | |
const result = await promise(); | |
completedPromises[idx] = result; | |
// Once all promises have been completed we resolve the ordered list of results. | |
if (Object.keys(promises).length === Object.keys(completedPromises).length) { | |
const orderedEntries = Object.entries(completedPromises).sort((a, b) => { | |
return a[0] > b[0]; | |
}); | |
const orderedValues = Object.values(orderedEntries).map((e => e[1])); | |
resolve(orderedValues); | |
} | |
} catch (e) { | |
return reject(e); | |
} | |
}); | |
}); | |
}; | |
const promisesWithDelay = [ | |
() => new Promise((resolve) => resolve(1)), | |
() => new Promise((resolve) => setTimeout(() => resolve('Delayed 2'), 1000)), | |
() => new Promise((resolve) => resolve(3)), | |
]; | |
promiseAll(promisesWithDelay).then(promises => { | |
console.log(promises); | |
}); | |
const promisesWithRejection = [ | |
() => new Promise((resolve) => resolve(1)), | |
() => new Promise((_, reject) => setTimeout(() => reject('Delayed Rejected'), 2000)), | |
() => new Promise((resolve) => resolve(3)), | |
]; | |
promiseAll(promisesWithRejection).then(() =>{}, error => { | |
console.error(error); | |
}); | |
// Output: | |
// [1, 'Delayed 2', 3] | |
// Delayed Rejected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment