Add Two Promises solution and explanation
9 more videos on this problem
Add Two Promises | Leetcode 2723 | Promises and Time | 30 Days of JavaScript #leetcode #javascriptLearn With Chirag · 18:13 · 3K views
2723. Add Two Promises - Leetcode JavaScript Solution with ExplanationEndeavour Monk · 7:51 · 2K views
#day12 | 2723 Add Two Promises | 30 Days of JavaScript |Leetcode-2723| What is Promises in JS? EasyCoding with Ankita · 23:31 · 798 views
Add Two Promises - LeetCode 2723 - JavaScriptScott Hacks Code · 2:49 · 665 views
LeetCode #2723 || Add Two Promises || Using javascriptHitesh · 1:31 · 337 views
2723. Add Two Promises | 30 dias de JavaScript no Leetcode #12Gustavo Caetano · 6:51 · 190 views
2723. Add Two Promises - Leetcode (Easy). 30 Days of JavaScript | День 12 | Сложение промисовdev tsx · 5:14 · 152 views
Leetcode - Add Two PromisesVinhNuwin · 3:19 · 149 views
30 days of JavaScript - Add Two PromisesCode With Bertrand · 13:30 · 149 views
LeetCode problems #700 (Ruby), #1890 (MySQL), #2723 (JavaScript), #1475 (Ruby)Code of Thunder · 49:27 · 124 views
The problem
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:
promise1andpromise2are promises that resolve with a number
Approach overview
Problem Overview: You receive two JavaScript promises, promise1 and promise2, each resolving to a number. The task is to return a new promise that resolves to the sum of their resolved values. The main challenge is coordinating asynchronous resolution correctly.
Approach 1: Chaining Promises (Sequential Resolution) (Time: O(1), Space: O(1))
This approach resolves the first promise and then resolves the second inside the .then() callback. After both values are available, return their sum. The logic uses promise chaining to control execution order. While straightforward, it waits for the first promise before starting to process the second, which can introduce unnecessary delay if both promises could resolve independently. This pattern is common when learning promises but is not the most efficient when tasks are independent.
Approach 2: Using Promise.all (Parallel Resolution) (Time: O(1), Space: O(1))
Promise.all() runs both promises concurrently and resolves once both are complete. It returns an array of resolved values in the same order as the input promises. You can destructure the results and return their sum. This approach avoids sequential waiting and is the most idiomatic way to combine multiple independent promises in JavaScript. Since both promises resolve simultaneously, total wait time equals the slower of the two operations.
Approach 3: Promise.all with Explicit Resolution Logic (Time: O(1), Space: O(1))
This variation still uses Promise.all(), but explicitly returns a new promise that resolves after computing the sum. Internally, it waits for both promises, then performs a simple arithmetic addition. The extra wrapping can be useful if additional asynchronous processing or validation is required before resolving the final result. Functionally it behaves the same as the standard Promise.all() approach but demonstrates how to build composed promise workflows.
Approach 4: Using async/await (Time: O(1), Space: O(1))
An async function allows promises to be written with synchronous-style code. Use await Promise.all([promise1, promise2]) to resolve both values, then return their sum. This approach keeps asynchronous logic easy to read and reduces nested callbacks. Many modern JavaScript codebases prefer async/await because it integrates cleanly with error handling and async control flow in async programming.
Recommended for interviews: Using Promise.all() is the expected solution. It resolves both promises concurrently and keeps the implementation concise. Chaining promises demonstrates understanding of asynchronous execution, but parallel resolution shows stronger familiarity with real-world JavaScript patterns.
Approach 1: Using Promise.all
function addTwoPromises(promise1, promise2) {
return Promise.all([promise1, promise2]).then(values => {
return values[0] + values[1];
});
}
// Example usage:
let promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20));
let promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60));
addTwoPromises(promise1, promise2).then(console.log); // Output: 7In this code, we first call `Promise.all` with an array of the two input promises promise1 and promise2. This returns a promise that resolves when both input promises resolve. We then use the `then` method to specify that when the promise resolves, it should sum the two resolved values and return the result.
Time Complexity: O(1) since promise creation and resolution are constant time operations.
Space Complexity: O(1) as we only store a fixed number of numbers.
Approach 2: Chaining Promises
function addTwoPromises(promise1, promise2) {
return promise1.then(value1 => {
return promise2.then(value2 => {
return value1 + value2;
});
});
}
// Example usage:
let promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50));
let promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30));
addTwoPromises(promise1, promise2).then(console.log); // Output: -2This code captures each promise's resolution value one after the other by chaining the then method, first resolving promise1, storing its value, and then resolving promise2, accumulating the sum and returning it.
Time Complexity: O(1) as each step essentially involves constant-time resolution.
Space Complexity: O(1) since we're working with a fixed number of variables.
Approach 3: Using Promise.all to resolve both promises simultaneously
This approach utilizes the Promise.all() method, which takes an array of promises and returns a new promise that resolves when all of the promises in the array have resolved.
In this method, you pass both promise1 and promise2 to Promise.all(). It waits for both promises to resolve, then combines their resolved values using array destructuring to sum them up within the then() method.
function addTwoPromises(promise1, promise2) {
return Promise.all([promise1, promise2]).then(values => {
return values[0] + values[1];
});
}
// Example Usage
const promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20));
const promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60));
addTwoPromises(promise1, promise2).then(console.log); // Outputs: 7The function addTwoPromises takes two promises and returns a new promise that resolves to the sum of the values resolved by the input promises. The Promise.all method is used to wait for both promises to resolve, and the resolved values are extracted as an array within the then method.
Time Complexity: O(1), as all operations inside the promises are essentially constant time operations.
Space Complexity: O(1), space usage is constant regardless of input sizes.
Approach 4: Using async/await for handling promise resolution
This approach employs async/await, a cleaner syntax for handling promises in JavaScript. By using an async function, you can await the resolution of both promise1 and promise2 to get their values before summing them up.
async function addTwoPromises(promise1, promise2) {
const value1 = await promise1;
const value2 = await promise2;
return value1 + value2;
}
// Example Usage
const promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50));
const promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30));
addTwoPromises(promise1, promise2).then(console.log); // Outputs: -2addTwoPromises is defined as an async function, meaning it returns a Promise and its execution can be paused using await. By awaiting both promise1 and promise2, the function captures their resolved values into value1 and value2. These are summed and the result is returned, thus promise chaining is implicit in every call.
Time Complexity: O(1), as the time taken by promise resolution does not scale with input data.
Space Complexity: O(1), as the function only stores a few values regardless of input.
Approach 5: Default Approach
async function addTwoPromises(
promise1: Promise<number>,
promise2: Promise<number>,
): Promise<number> {
return (await promise1) + (await promise2);
}
/**
* addTwoPromises(Promise.resolve(2), Promise.resolve(2))
* .then(console.log); // 4
*/Complexity comparison
| Approach | Complexity |
|---|---|
| Using Promise.all | Time Complexity: O(1) since promise creation and resolution are constant time operations. |
| Chaining Promises | Time Complexity: O(1) as each step essentially involves constant-time resolution. |
| Using Promise.all to resolve both promises simultaneously | Time Complexity: O(1), as all operations inside the promises are essentially constant time operations. |
| Using async/await for handling promise resolution | Time Complexity: O(1), as the time taken by promise resolution does not scale with input data. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Chaining Promises | O(1) | O(1) | When demonstrating basic promise chaining or sequential async execution |
| Promise.all (Parallel) | O(1) | O(1) | Best choice when promises are independent and can resolve concurrently |
| Promise.all with Wrapper Promise | O(1) | O(1) | Useful when adding extra async processing before resolving the final result |
| Async/Await with Promise.all | O(1) | O(1) | Preferred in modern JavaScript for readability and structured async control flow |
Frequently asked questions
Is Add Two Promises easy or hard?
Add Two Promises is considered an easy problem. It mainly tests basic knowledge of JavaScript promises and asynchronous handling rather than complex algorithms or data structures.
Add Two Promises Python/Java solution
The original problem targets JavaScript because it relies on Promise behavior. In Python, a similar pattern would use asyncio.gather with coroutines, while Java would use CompletableFuture.allOf to combine asynchronous computations.
How to solve Add Two Promises in O(1)?
Use Promise.all to resolve both promises simultaneously. Once both values are returned, add them and return the result. The operation performs a constant number of asynchronous resolutions and arithmetic operations, giving O(1) time and space complexity.
What is the best approach for Add Two Promises?
Using Promise.all is the best approach. It resolves both promises concurrently and returns their results in an array, allowing you to compute the sum immediately. This keeps the implementation concise and avoids unnecessary sequential waiting.
Is Add Two Promises asked at Google/Amazon/Meta?
Problems involving promises and async control flow frequently appear in JavaScript interviews at companies like Google, Amazon, and Meta. While this exact problem may vary, understanding Promise.all and async/await is commonly tested.
What data structure is used in Add Two Promises?
No specialized data structure is required. The problem focuses on JavaScript asynchronous primitives such as Promise objects and utilities like Promise.all that coordinate multiple promise resolutions.
What is the time complexity of Add Two Promises?
The computational complexity is O(1) time and O(1) space because only two values are processed. In terms of asynchronous execution, the total wait time equals the slower of the two promises since they can resolve in parallel.
