JS Machine Coding Questions — Implementations You Must Know
Promise.all polyfill
- Resolve when every input settles successfully; reject with the first rejection (fail-fast). Output order matches input order.
- Key insight: Promise.resolve each item so non-thenables count as fulfilled values. Track how many are still pending; on the last success, resolve the array.
- Gotcha: Empty iterable must resolve to [], not hang.
- Gotcha: First rejection short-circuits — remaining work may still run, but the returned promise is already rejected.
- Gotcha: Preserve index order even if promises finish out of order (hence results[i]).
1Promise.myAll = function (iterable) {
2 return new Promise((resolve, reject) => {
3 const arr = Array.from(iterable);
4 const n = arr.length;
5 if (n === 0) { resolve([]); return; }
6
7 const results = new Array(n);
8 let settled = 0;
9
10 arr.forEach((item, i) => {
11 Promise.resolve(item).then(
12 (value) => {
13 results[i] = value;
14 settled++;
15 if (settled === n) resolve(results);
16 },
17 reject
18 );
19 });
20 });
21};