SIMPLE | 9 LINES SOLUTION | SEVERAL PROMISES IN PARALLEL 🎯💯❤️‍🔥🏆🥇 JAVASCRIPT ✅🕶🤏📚 🧠 🎓
2721. Execute Asynchronous Functions in Parallel\n\n\uD83E\uDEB4 Difficulty: Medium\n\n\uD83D\uDC81\uD83C\uDFFB\u200D\u2640\uFE0F All my solved LeetCode problem
# 2721. Execute Asynchronous Functions in Parallel\n\n\uD83E\uDEB4 Difficulty: `Medium`\n\n\uD83D\uDC81\uD83C\uDFFB\u200D\u2640\uFE0F All my solved LeetCode problems on GitHub: [rayanasales/leetcode](https://github.com/rayanasales/leetcode)\n\n\u2764\uFE0F\u200D\uD83D\uDD25\u2764\uFE0F\u200D\uD83D\uDD25\u2764\uFE0F\u200D\uD83D\uDD25 If it\'s help, please up \uD83D\uDD1D vote! \u2764\uFE0F\u200D\uD83D\uDD25\u2764\uFE0F\u200D\uD83D\uDD25\u2764\uFE0F\u200D\uD83D\uDD25\n\n---\n\n## Solution in javascript\n\n```javascript []\nvar promiseAll = function (functions) {\n  return new Promise((resolve, reject) => {\n    const results = []; // Array to store results in the original order\n    let completedPromises = 0; // Counter to track how many promises have been resolved\n\n    functions.forEach((fn, i) => {\n      fn()\n        .then((result) => {\n          results[i] = result; // Store result at the correct index\n          completedPromises++; // Increment counter for each resolved promise\n          if (completedPromises === functions.length) resolve(results); // If all promises are done, resolve with the results array\n        })\n        .catch(reject); // If any promise fails, reject immediately\n    });\n  });\n};\n```\n\n# Explanation\n\n### **What Are Promises?**\n\n- **Promises**\xA0in JavaScript are a way to handle asynchronous operations, which are operations that take some time to complete, such as fetching data from a server or waiting for a timer.\n- A promise can be in one of three states:\n  - **Pending:**\xA0The operation is still ongoing.\n  - **Resolved (Fulfilled):**\xA0The operation completed successfully, and the promise now has a result.\n  - **Rejected:**\xA0The operation failed, and the promise has an error or reason for the failure.\n- Promises allow us to write code that can react to these different outcomes, using\xA0`.then()`\xA0for successful resolutions and\xA0`.catch()`\xA0for errors.\n\n### **Strategy Used in the Code:**\n\n1. **Creating a New Promise:**\n   - The code starts by creating a new promise. This is the promise that will eventually hold the results of all the asynchronous operations in the\xA0`functions`\xA0array. This promise will either resolve (success) when all the individual promises have finished successfully or reject (failure) if any one of them fails.\n2. **Tracking Results:**\n   - We need to keep track of the results of each asynchronous operation. To do this, we create an empty\xA0`results`\xA0array. This array will store the results in the same order as the original\xA0`functions`\xA0array, ensuring that the final output respects the original order.\n3. **Counting Completed Promises:**\n   - We also set up a counter called\xA0`completedPromises`\xA0to track how many of the promises have finished. This counter helps us know when all the promises have completed successfully so that we can resolve our main promise with the results.\n4. **Handling Each Function:**\n   - We loop over the\xA0`functions`\xA0array using\xA0`forEach`. For each function, we:\n     - Call the function to start the asynchronous operation. The function returns a promise.\n     - Use\xA0`.then()`\xA0to handle the case where the promise resolves successfully. When a promise resolves, we store its result in the\xA0`results`\xA0array at the correct position (using the index\xA0`i`\xA0from the loop).\n     - Increment the\xA0`completedPromises`\xA0counter to keep track of how many promises have successfully completed. If this counter equals the total number of functions, it means all promises are done, and we resolve the main promise with the\xA0`results`\xA0array.\n     - Use\xA0`.catch()`\xA0to handle the case where any promise fails. If any promise rejects, we immediately reject the main promise with the error, meaning the whole operation fails.\n5. **Final Output:**\n   - If all promises resolve successfully, the final output is an array of results, ordered according to the original order of the functions. If any promise fails, the operation stops immediately, and the error is propagated.\n\n---\n\n# Please UPVOTE if this was helpful \uD83D\uDD1D\uD83D\uDD1D\uD83D\uDD1D\u2764\uFE0F\u2764\uFE0F\u2764\uFE0F\n\nand check it out all my solved LeetCode problems on GitHub: [rayanasales/leetcode](https://github.com/rayanasales/leetcode) \uD83E\uDD19\uD83D\uDE1A\uD83E\uDD18\n\n![image.png](https://assets.leetcode.com/users/images/57bce3b1-56e2-4c20-9cdf-b61fef26b93b_1725494158.6252415.png)\n
['JavaScript']