Recent Posts
Recent Comments
게으른개발너D
[Promise] Add Two Promises (feat. all) ⭐️ 본문
https://leetcode.com/problems/add-two-promises/description/
Add Two Promises - LeetCode
Can you solve this real interview question? Add Two Promises - 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. E
leetcode.com
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.
Example 1:
Input:
promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)),
promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60))
Output: 7
Explanation: The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem.
Example 2:
Input:
promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)),
promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30))
Output: -2
Explanation: The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2.
Constraints:
- promise1 and promise2 are promises that resolve with a number
solution
/**
* @param {Promise} promise1
* @param {Promise} promise2
* @return {Promise}
*/
var addTwoPromises = async function(promise1, promise2) {
return Promise.all([promise1, promise2])
.then(value => value[0] + value[1]);
};
/**
* addTwoPromises(Promise.resolve(2), Promise.resolve(2))
* .then(console.log); // 4
*/
'알고리즘 > 과제' 카테고리의 다른 글
[Function] Debounce ⭐️ (0) | 2023.07.04 |
---|---|
[Class] Calculator with Method Chaining (method에 return 값) ⭐️ (0) | 2023.07.04 |
[Funtions, Timeout] Execute Cancellable Function With Delay (0) | 2023.07.04 |
[Function, Closure] To Be Or Not To Be (0) | 2023.07.04 |
[Array] Array Wrapper (method, prototype 만들기) ⭐️ (0) | 2023.07.04 |
Comments