Skip to content

Commit 40a6fce

Browse files
authored
code added
1 parent be46b4a commit 40a6fce

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

12_addTwoPromises.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Question Link: https://leetcode.com/problems/add-two-promises/description/?envType=study-plan-v2&envId=30-days-of-javascript
2+
// Solution Link: https://leetcode.com/problems/add-two-promises/solutions/5439365/2-different-easy-javascript-solution/
3+
4+
/*
5+
2723. Add Two Promises
6+
7+
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.
8+
9+
Example 1:
10+
Input:
11+
promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)),
12+
promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60))
13+
Output: 7
14+
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.
15+
16+
Example 2:
17+
Input:
18+
promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)),
19+
promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30))
20+
Output: -2
21+
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.
22+
23+
Constraints:
24+
promise1 and promise2 are promises that resolve with a number
25+
*/
26+
27+
28+
29+
/**
30+
* @param {Promise} promise1
31+
* @param {Promise} promise2
32+
* @return {Promise}
33+
*/
34+
35+
/*
36+
// 1st Approach
37+
var addTwoPromises = async function(promise1, promise2) {
38+
const num1 = await promise1;
39+
const num2 = await promise2;
40+
41+
return num1 + num2;
42+
};
43+
*/
44+
45+
// 2nd Approach
46+
var addTwoPromises = async function(promise1, promise2) {
47+
const [num1, num2] = await Promise.all([promise1, promise2]);
48+
49+
return num1 + num2;
50+
};
51+
52+
/**
53+
* addTwoPromises(Promise.resolve(2), Promise.resolve(2))
54+
* .then(console.log); // 4
55+
*/

0 commit comments

Comments
 (0)