Jeff的隨手筆記

學習當一個前端工程師

0%

用LeetCode寫日記-Day12

今天的題目有點是誤打誤撞寫出來的,典型的有想法但不會語法。

Day12: 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.

問題難度:Easy

問題限制:

promise1 and promise2 are promises that resolve with a number

我的解題過程:

建立一個新的 Promise,該 Promise 為兩個給定 Promise 的值總和。

這題是我的知識盲區了,我知道Promise,也知道async await ,但卡在如何讓兩個Promise一次執行。
因此只好先讓兩個單獨執行,然後在相加。

1
2
3
const pro1 = await promise1
const pro2 = await promise2
return pro1 + pro2

老實說執行成功有點讓我嚇到XDD

其他解答

1
2
3
4
5
6
7
var addTwoPromises = async function(promise1, promise2) {
// Wait for both promises to resolve and retrieve their values
const [value1, value2] = await Promise.all([promise1, promise2]);

// Return a new promise that resolves with the sum of the values
return value1 + value2;
};

結論

其他解法的回答方式是我一開始想要的,依稀有印象之前學習時有看過類似的方法,但真的沒有過所以就忘掉了。

之所以說有點嚇到是因為真的有一陣子沒碰過promise了,有點忘記他要怎麼執行,因此先試打腦袋裡出現的想法,沒想到這次出現的想法居然是正確答案,這也印證了一件事,我真的讀書沒有讀熟!