面试题 Interview Question
实现一个
promiseAll
函数,行为与原生Promise.all
一致。
Implement apromiseAll
function that behaves like the nativePromise.all
.
要求 Requirements
-
promiseAll(promises)
接收一个由 Promise 或普通值组成的可迭代对象(如数组)
promiseAll(promises)
takes an iterable (e.g., an array) of values, which may be Promises or regular values. -
返回一个新的 Promise,满足以下条件:
It returns a new Promise that:- 当所有 Promise 都成功时,按顺序返回它们的结果数组
Resolves with an array of results in the same order as input, when all Promises resolve - 如果有任何一个 Promise 失败,则整个 Promise 立即失败
Rejects immediately if any input Promise rejects
- 当所有 Promise 都成功时,按顺序返回它们的结果数组
-
不使用内置的
Promise.all
Do not use the built-inPromise.all
-
代码应遵循纯函数式风格,不使用
this
Use pure functional style; do not rely onthis
参考答案 Reference Solution
function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const results = [];
let completed = 0;
const total = iterable.length;
if (total === 0) return resolve([]);
iterable.forEach((item, index) => {
Promise.resolve(item)
.then(value => {
results[index] = value;
completed++;
if (completed === total) {
resolve(results);
}
})
.catch(reject); // 一旦有失败,直接 reject
});
});
}
示例 Example
const p1 = Promise.resolve(1);
const p2 = 42;
const p3 = new Promise(resolve => setTimeout(() => resolve('done'), 100));
promiseAll([p1, p2, p3]).then(result => {
console.log(result); // 输出 Output: [1, 42, 'done']
});
promiseAll([Promise.resolve(1), Promise.reject('error')])
.then(console.log)
.catch(err => console.error('失败了 Failed:', err));
// 输出:失败了 Failed: error
面试考察点 Interview Focus
- 对 Promise 并发控制机制的理解
Understanding of how Promises handle concurrency and resolution - 异步流程控制能力(顺序控制 vs. 并发执行)
Ability to manage asynchronous flow and order guarantees - 错误处理与边界情况处理能力
Ability to handle errors and edge cases robustly