Skip to content

Instantly share code, notes, and snippets.

@AleKiller21
Created April 13, 2022 05:57
Show Gist options
  • Save AleKiller21/84ed1ed31fc82a085c61a0f313f0a95b to your computer and use it in GitHub Desktop.
Save AleKiller21/84ed1ed31fc82a085c61a0f313f0a95b to your computer and use it in GitHub Desktop.
Asyncrhonicity JS Interview Problem
const updatedCollection = [];
const originalCollection = [1,2,3,4,5];
const pushAsync = (collection, value) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Multiplying value: ${value} and inserting it into the updated collection`);
collection.push(value * 2);
resolve();
}, value);
})
}
//Wrong Implementation. Present this to interviewee so that he can see the wrong behavior and proceed to fix it.
// originalCollection.forEach(async (value) => {
// await pushAsync(updatedCollection, value);
// });
// console.log('This is the content of the updated collection: ', updatedCollection);
//Solution:
const promisesCollection = originalCollection.map(value => pushAsync(updatedCollection, value));
Promise.all(promisesCollection).then(() => console.log('This is the content of the updated collection: ', updatedCollection));
//The issue here is that the forEach function will not wait for the promise returned by the asynchronous function to settle. It will just execute the callback but it won't wait for the returned promise to get settled. Therefore, one way to solve this would be by collecting all the triggered promises in an array and then wait for all of them to get settled. In this implementation, we're waiting for all of them to get resolved without worrying about the rejection of any of them. This scenario is not important for this exercise.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment