概要
この記事は、LeetCodeの30 Days of JavaScriptのPromises and Time(全8問)を1問ずつ解いて
非同期処理をマスターするシリーズの第1弾です。
問題:2723. Add Two Promise
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
つまり、2つの Promise1 と Promise2 があるとき、新しい Promise を2つの数値の合計で返す問題。
例1
入力:
promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)),
promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60))
出力:7
解説:promise1のresolve(2)とpromise2のresolve(5)を合計すると7になる(2+5)
※この問題では、返された Promise が解決する時間は判断されませんとの記載があるので考慮しません。
必要な知識
- 非同期処理のawait
- Promise.all
実装例
パターン1
Runtime:53ms
Memory:42.89MB
type P = Promise<number>
async function addTwoPromises(promise1: P, promise2: P): P {
return await promise1 + await promise2
};
awaitキーワードを使用して、それぞれのPromiseの結果を個別に持ち合わせて計算します。
パターン2
Runtime:70ms
Memory:42.96MB
type P = Promise<number>
async function addTwoPromises(promise1: P, promise2: P): P {
return new Promise<number>((resolve, reject) => {
Promise.all([promise1, promise2])
.then(([result1, result2]) => {
const sum = result1 + result2;
resolve(sum);
})
.catch(reject);
});
};
Promise.allメソッドにより、引数で与えられた2つのPromiseオブジェクトが両方とも完了するまで待ちます。両方のPromiseが完了した場合、その結果を配列として受け取ることができます。
また、その後配列の要素を足し合わせ、その結果をresolveメソッドで返します。もしPromiseのいずれかがエラーとなった場合は、エラーをrejectメソッドで返します。
ポイント
パターン1
awaitキーワードを使用して、それぞれのPromiseの結果を個別に待ち合わせてから合計を計算しているため、返り値はPromiseではなく、計算結果そのものとなります。
パターン2
Promise.allメソッドを使用して、2つのPromiseの結果を待ち合わせてから合計を計算しているため、結果は新しいPromiseとして返されます。
新しいPromiseとして返すということなので、こちらの方が問題文の答えとして適切かもしれません。