How does Promise.all() method works?
Intuition\nThe first thought was looping through an array inside a promise, for each iteration execute the function which returns a promise which when resolved,
# Intuition\nThe first thought was looping through an array inside a promise, for each iteration execute the function which returns a promise which when resolved, we need to collect the value into an array and reject if any error in catch clause. so for this we need two variables one for result and another for error.\n\nif error occurs stop the execution and return the error else continue loop and resolve the resulting array.\n\n# Approach\nMy function is returning a promise which initialises a result and error variable. following that, we need to interate through the functions array. For each interation, run the function and on its resolve, we need to collect the value in the results array till the loop ends. \n\nIf during this process, there is a catch clause, reject the error and stop execution.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```typescript []\ntype Fn<T> = () => Promise<T>\n\nfunction promiseAll<T>(functions: Fn<T>[]): Promise<T[]> {\n    return new Promise((res, rej) => {\n        if(!functions.length) res([])\n        const results = [];\n        let error = null\n        let resolved = 0;\n        for(let i = 0; i < functions.length; i ++) {\n            functions[i]().then((val) => {\n                results[i] = val;\n                resolved ++;\n                if(resolved === functions.length) {\n                    res(results);\n                }\n            }).catch((e) => {\n                rej(e)\n            })\n        }\n    })\n};\n\n/**\n * const promise = promiseAll([() => new Promise(res => res(42))])\n * promise.then(console.log); // [42]\n */\n```
['TypeScript', 'JavaScript']