Add Two Promises | #2723 | LeetCode Solution

Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode

Problem : Add Two Promises | #2723 | LeetCode

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.


Solution:

    /**

     * @param {Promise} promise1

     * @param {Promise} promise2

     * @return {Promise}

     */

    var addTwoPromises = async function (promise1, promise2) {

        const [result1, result2] = await Promise.all([promise1, promise2]);

        return Promise.resolve(result1 + result2);

    };


    /**

     * addTwoPromises(Promise.resolve(2), Promise.resolve(2))

     *   .then(console.log); // 4

     */



Explanation:

Let's break down the code step by step:


1. `addTwoPromises` is a function that takes two promises, `promise1` and `promise2`, as arguments.


2. Inside the `addTwoPromises` function:

   - `await Promise.all([promise1, promise2]);` - This line uses `Promise.all` to wait for both `promise1` and `promise2` to resolve. `Promise.all` takes an array of promises and returns a new promise that resolves with an array of their resolved values. In this case, `result1` will hold the resolved value of `promise1`, and `result2` will hold the resolved value of `promise2`.


   - `return Promise.resolve(result1 + result2);` - After both promises have resolved, this line calculates the sum of `result1` and `result2`. Then, it returns a new promise using `Promise.resolve` that resolves with the sum as its value.


3. The `addTwoPromises` function is then called with two promises:

   

   addTwoPromises(Promise.resolve(2), Promise.resolve(2))

   

   - `Promise.resolve(2)` creates a promise that immediately resolves with the value `2`.

   - `addTwoPromises` is called with two such promises.


4. `.then(console.log)` - This part of the code attaches a `.then` callback to the result of `addTwoPromises`. When the promise returned by `addTwoPromises` resolves (which will happen after both `Promise.resolve(2)` promises have resolved and their values have been added together), the `.then` callback is executed with the result as an argument.


5. `console.log` is used to output the result, so the sum of the two resolved values (`2 + 2`) is printed to the console, resulting in `4` being displayed.


In summary, this code defines a function `addTwoPromises` that takes two promises, waits for them to resolve using `Promise.all`, calculates their sum, and returns a new promise that resolves with the sum. When you call `addTwoPromises` with two promises that resolve to `2`, it returns a promise that eventually resolves to `4`, and `console.log` is used to print that value to the console.





Related Blogs
Generate Fibonacci Sequence - JavaScript | Hackerank
Author: neptune | 07th-Apr-2023
#JavaScript #Hackerrank
Write a JavaScript function fibonacciSequence() to generate a FIbonacci sequence...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Array Reduce Transformation | #2626 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array...

Filter Elements from Array | #2634 | LeetCode Solution
Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
#JavaScript
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?
Author: neptune | 31st-Jul-2024
#JavaScript #API
Building a blogging website using React, Node.js, and Jamstack architecture was a rewarding experience...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
#JavaScript
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

How to Perform Unit Testing in React Components with Examples?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
Unit testing in React is an essential practice to ensure the reliability and robustness of your components...

Do you know ! How to manage State in Functional & Class Components in React ?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
State management in React has evolved significantly with the introduction of Hooks...

How to Get Started with Jamstack: A Comprehensive Guide?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Getting started with Jamstack involves choosing the right tools, setting up a structured development environment...

Why, What, and When: Understanding Jamstack?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Jamstack represents a modern approach to web development that addresses many of the challenges faced by traditional architectures...

View More