Beats 96.4% in 59ms
Intuition\n Describe your first thoughts on how to solve this problem. \nWe aim to execute an array of asynchronous functions in parallel, collecting their resu
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe aim to execute an array of asynchronous functions in parallel, collecting their results. If any function fails, the whole execution should stop and return the error immediately.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe function promiseAll manually handles the process of resolving or rejecting promises. It iterates over each function in the array, invoking it and attaching a .then to store results and track completions. If all promises succeed, the collected results are returned in order. If any promise rejects, the first encountered rejection is propagated immediately.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n): Each of the n promises is executed and either resolved or rejected.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n): We store n results in an array, corresponding to the number of promises in the input array.\n\n# Code\n```javascript []\n/**\n * @param {Array<Function>} functions\n * @return {Promise<any>}\n */\nvar promiseAll = function(functions) {\n    return new Promise((resolve, reject) => {\n        let results = [], completed = 0;\n        functions.forEach((fn, i) => fn()\n            .then(res => {\n                results[i] = res;\n                if (++completed === functions.length) resolve(results);\n            })\n            .catch(reject)\n        );\n    });\n}\n/**\n * const promise = promiseAll([() => new Promise(res => res(42))])\n * promise.then(console.log); // [42]\n */\n```
['JavaScript']