Study - Problems(IT)/LeetCode - JavaScript

2723. Add Two Promises

Dev.D 2024. 11. 7. 18:26

Given two promises promise1 and promise2, return a new promise. promise1 and promise2 will both resolve with a number. The returned promise should resolve with the sum of the two numbers.

 

* Solution

/**
   * @param {Promise} promise1
   * @param {Promise} promise2
   * @return {Promise}
*/
var addTwoPromises = async function(promise1, promise2) {
        return (await promise1 + await promise2)
};

 

다른 이들의 답이 궁금하여 확인해 본 글 중 다음 설루션이 있었다.

 

* Solution

 

/**
   * @param {Promise} promise1
   * @param {Promise} promise2
   * @return {Promise} */
var addTwoPromises = async function(promise1, promise2) { // Wait for both promises to resolve and retrieve their values
      const [value1, value2] = await Promise.all([promise1, promise2]); // Return a new promise that resolves with the sum of the values
      return value1 + value2;
}; 

 

Promise.all()함수를 사용할 생각을 했다니..

 

무작정 풀고 본다는 생각을 다시 한번 깨우치는 계기가 되었다.

 

[참고] https://leetcode.com/problems/add-two-promises/solutions/3698863/easy-solution-2723-add-two-promises-level-up-your-js-skills

'Study - Problems(IT) > LeetCode - JavaScript' 카테고리의 다른 글

2624.Memoize  (2) 2024.11.06