LeetCode 题解工作台

并行执行异步函数

给定一个异步函数数组 functions ,返回一个新的 promise 对象 promise 。数组中的每个函数都不接受参数并返回一个 promise。所有的 promise 都应该并行执行。 promise resolve 条件: 当所有从 functions 返回的 promise 都成功的并…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

中等 · Execute Asynchronous Functions in Parallel core interview pattern

bolt

答案摘要

async function promiseAll<T>(functions: (() => Promise<T>)[]): Promise<T[]> { return new Promise<T[]>((resolve, reject) => {

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 Execute Asynchronous Functions in Parallel core interview pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个异步函数数组 functions,返回一个新的 promise 对象 promise。数组中的每个函数都不接受参数并返回一个 promise。所有的 promise 都应该并行执行。

promise resolve 条件:

  • 当所有从 functions 返回的 promise 都成功的并行解析时。promise 的解析值应该是一个按照它们在 functions 中的顺序排列的 promise 的解析值数组。promise 应该在数组中的所有异步函数并行执行完成时解析。

promise reject 条件:

  • 当任何从 functions 返回的 promise 被拒绝时。promise 也会被拒绝,并返回第一个拒绝的原因。

请在不使用内置的 Promise.all 函数的情况下解决。

 

示例 1:

输入:functions = [
  () => new Promise(resolve => setTimeout(() => resolve(5), 200))
]
输出:{"t": 200, "resolved": [5]}
解释:
promiseAll(functions).then(console.log); // [5]

单个函数在 200 毫秒后以值 5 成功解析。

示例 2:

输入:functions = [
    () => new Promise(resolve => setTimeout(() => resolve(1), 200)), 
    () => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100))
]
输出:{"t": 100, "rejected": "Error"}
解释:由于其中一个 promise 被拒绝,返回的 promise 也在同一时间被拒绝并返回相同的错误。

示例 3:

输入:functions = [
    () => new Promise(resolve => setTimeout(() => resolve(4), 50)), 
    () => new Promise(resolve => setTimeout(() => resolve(10), 150)), 
    () => new Promise(resolve => setTimeout(() => resolve(16), 100))
]
输出:{"t": 150, "resolved": [4, 10, 16]}
解释:所有的 promise 都成功执行。当最后一个 promise 被解析时,返回的 promise 也被解析了。

 

提示:

  • 函数 functions 是一个返回 promise 的函数数组
  • 1 <= functions.length <= 10
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
async function promiseAll<T>(functions: (() => Promise<T>)[]): Promise<T[]> {
    return new Promise<T[]>((resolve, reject) => {
        let cnt = 0;
        const ans = new Array(functions.length);
        for (let i = 0; i < functions.length; ++i) {
            const f = functions[i];
            f()
                .then(res => {
                    ans[i] = res;
                    cnt++;
                    if (cnt === functions.length) {
                        resolve(ans);
                    }
                })
                .catch(err => {
                    reject(err);
                });
        }
    });
}

/**
 * const promise = promiseAll([() => new Promise(res => res(42))])
 * promise.then(console.log); // [42]
 */
speed

复杂度分析

指标
时间O(N)
空间O(N)
psychology

面试官常问的追问

外企场景
  • question_mark

    Ensure the candidate handles both resolve and reject scenarios effectively.

  • question_mark

    Look for the correct usage of parallel execution strategies, such as Promise.all().

  • question_mark

    Test whether the candidate can track the timing of executions and handle errors gracefully.

warning

常见陷阱

外企场景
  • error

    Not handling rejections properly, causing the promise to hang or resolve incorrectly.

  • error

    Incorrectly tracking the execution time or values from individual functions.

  • error

    Not using a structure that ensures the final promise resolves or rejects based on all functions.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Implementing this solution using Promise.allSettled() instead of Promise.all() for a different error handling approach.

  • arrow_right_alt

    Handling timeouts for individual promises and rejecting the overall promise if a timeout occurs.

  • arrow_right_alt

    Modifying the function to return results in the same order as the functions were originally given, regardless of their resolution time.

help

常见问题

外企场景

并行执行异步函数题解:Execute Asynchronous Fu… | LeetCode #2721 中等