문제

Given an array of asynchronous functions functions, return a new promise promise. Each function in the array accepts no arguments and returns a promise. All the promises should be executed in parallel.

promise resolves:

  • When all the promises returned from functions were resolved successfully in parallel. The resolved value of promise should be an array of all the resolved values of promises in the same order as they were in the functions. The promise should resolve when all the asynchronous functions in the array have completed execution in parallel.

promise rejects:

  • When any of the promises returned from functions were rejected. promise should also reject with the reason of the first rejection.

Please solve it without using the built-in Promise.all function.

 

https://leetcode.com/problems/execute-asynchronous-functions-in-parallel/

 

예시

 

틀린 코드

/**
	틀린 코드
**/
var promiseAll = function(functions) {
    return new Promise((resolve, reject) => {
        const arr = [];
        
        
        functions.forEach((promise)=>{
            promise()
            .then((value) => {
                arr.push(value);

                if(arr.length === functions.length){
                    resolve(arr);
                }
            })
            .catch((err) => {
                reject(err);
            });
        });
        
        
    });
};

처음에 시도했던 코드인데, 틀렸다. 해당 예시를 실행해보니, arr 배열에 들어가는 resolve된 값의 순서가 promise의 순서와 달랐다. 현재 코드대로라면, functions 배열에 있는 프로미스의 실행이 완료되면 arr에 값이 push 되는데, 어떤 프로미스가 먼저 실행이 완료되는지 알지 못하기 때문에 순서가 바뀔 수 있던 것이다. 따라서, arr에 push 하는 방법 대신, index를 직접 지정해서 순서가 바뀌지 않도록 해주었다. (아래 코드 참조)

 

정답 코드

/**
 * @param {Array<Function>} functions
 * @return {Promise<any>}
 */
var promiseAll = function(functions) {
    return new Promise((resolve, reject) => {
        const arr = Array(functions.length);
        
        let solveCnt = 0;
        
        functions.forEach((promise, idx)=>{
            promise()
            .then((value) => {
                arr[idx] = value;
                solveCnt++;

                if(solveCnt === functions.length){
                    resolve(arr);
                }
            })
            .catch((err) => {
                reject(err);
            });
        });
        
        
    });
};

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

index를 이용해 arr에 값을 넣어주었고, 모든 promise가 다 실행 완료가 됐을 때 resolve 해야 하므로 solveCnt라는 변수로 실행 완료된 promise의 개수를 세었다.

728x90

'Algorithm > leetcode' 카테고리의 다른 글

[leetcode][TS] 9. Palindrome Number  (0) 2024.08.18
[leetcode][TS] 1. Two Sum  (0) 2024.08.14
[leetcode][JS] 2624. Snail Traversal  (0) 2024.08.01
[leetcode][JS] 2722. Join Two Arrays by ID  (0) 2024.07.30
[leetcode][JS] 2727. Is Object Empty  (0) 2024.02.13

+ Recent posts