LeetCode 题解工作台
两个 Promise 对象相加
给定两个 promise 对象 promise1 和 promise2 ,返回一个新的 promise。 promise1 和 promise2 都会被解析为一个数字。返回的 Promise 应该解析为这两个数字的和。 示例 1: 输入: promise1 = new Promise(resolve…
0
题型
2
代码语言
0
相关题
当前训练重点
简单 · add·双·promises·core·interview·pattern
答案摘要
async function addTwoPromises( promise1: Promise<number>,
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 add·双·promises·core·interview·pattern 题型思路
题目描述
promise1 和 promise2,返回一个新的 promise。promise1 和 promise2 都会被解析为一个数字。返回的 Promise 应该解析为这两个数字的和。
示例 1:
输入: promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)), promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60)) 输出:7 解释:两个输入的 Promise 分别解析为值 2 和 5。返回的 Promise 应该解析为 2 + 5 = 7。返回的 Promise 解析的时间不作为判断条件。
示例 2:
输入: promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)), promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30)) 输出:-2 解释:两个输入的 Promise 分别解析为值 10 和 -12。返回的 Promise 应该解析为 10 + -12 = -2。
提示:
promise1 和 promise2都是被解析为一个数字的 promise 对象
解题思路
方法一
var addTwoPromises = async function (promise1, promise2) {
return (await promise1) + (await promise2);
};
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate demonstrates an understanding of promise resolution order.
- question_mark
Look for efficient handling of asynchronous behavior and edge cases.
- question_mark
Evaluate the candidate's ability to implement solutions using modern JavaScript features like async/await.
常见陷阱
外企场景- error
Not properly handling the case where one promise resolves before the other, potentially causing issues with the addition.
- error
Failing to consider edge cases where the promises resolve to non-numeric values.
- error
Using nested .then() chains unnecessarily, making the code harder to maintain and read.
进阶变体
外企场景- arrow_right_alt
Modify the problem to add more than two promises.
- arrow_right_alt
Change the problem to handle promises that resolve to objects instead of numbers.
- arrow_right_alt
Have the promises resolve after different time intervals and measure the time it takes for the sum to be returned.