2723. 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.
?
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.文章來源:http://www.zghlxwxcb.cn/news/detail-502099.html
Constraints:
- promise1 and promise2 are promises that resolve with a number
From: LeetCode
Link: 2723. Add Two Promises
文章來源地址http://www.zghlxwxcb.cn/news/detail-502099.html
Solution:
Ideas:
This function takes two promises as input, and returns a new promise that resolves with the sum of the two numbers. The function works by first chaining the two promises together. This means that when the first promise resolves, the second promise will be executed. Once the second promise resolves, the sum of the two numbers will be calculated and the new promise will be resolved.
Code:
/**
* @param {Promise} promise1
* @param {Promise} promise2
* @return {Promise}
*/
var addTwoPromises = async function(promise1, promise2) {
return new Promise((resolve, reject) => {
promise1.then((num1) => {
promise2.then((num2) => {
resolve(num1 + num2);
});
});
});
};
/**
* addTwoPromises(Promise.resolve(2), Promise.resolve(2))
* .then(console.log); // 4
*/
到了這里,關(guān)于LeetCode //2723. Add Two Promises (Day 30 of LC JavaScript Challenage)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!