All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2701_2800.s2721_execute_asynchronous_functions_in_parallel.solution.ts Maven / Gradle / Ivy

The newest version!
// #Medium #2023_09_18_Time_67_ms_(84.73%)_Space_43.6_MB_(15.83%)

async function promiseAll(functions: (() => Promise)[]): Promise {
    const resolved = []
    let counter = 0

    return new Promise((resolve, reject) => {
        for (let i = 0; i < functions.length; i++) {
            functions[i]()
                .then((res) => {
                    // must specify index of array
                    resolved[i] = res
                    counter++
                    if (counter === functions.length) {
                        resolve(resolved)
                    }
                })
                .catch((err) => {
                    reject(err)
                })
        }
    })
}

/*
 * const promise = promiseAll([() => new Promise(res => res(42))])
 * promise.then(console.log); // [42]
 */

export { promiseAll }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy