Unicorns VO 面试真题解析:Implement Promise.all(Promise、异步控制、前端编程)

30次阅读
没有评论

Implement Promise.all

Promise.all() takes an iterable of Promise objects and returns a single Promise. The returned Promise resolves to an array of results when all input Promises have resolved. It rejects as soon as any input Promise rejects, with the reason from the first rejected Promise.

Please implement a Promise.all() method.

Input Description

An array composed of multiple Promise instances.

Output Description

A Promise instance.

Example 1:

Input:  head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input:  head = [1], n = 1
Output: []

Example 3:

Input:  head = [1,2], n = 1
Output: [1]

这道题考察的是前端异步控制中的 Promise.all 实现。核心思路是:遍历输入的 Promise 数组,按原始顺序保存每个 Promise 的结果;当所有 Promise 都成功完成时,返回一个包含所有结果的新 Promise;如果其中任意一个 Promise 失败,则立即以该失败原因 reject,并且只返回第一次失败的信息。实现时通常需要用索引记录结果位置,并用计数器判断是否全部完成。

正文完
 0