These are the notes for JavaScript Coding Questions, episode 22, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Last episode we wrote sleep, retry and timeout. Today is promise questions, part two, with three classic interview questions: write your own Promise.all, write your own Promise.allSettled, and run many async tasks, but only a few at a time (a concurrency limit). On the way: why push mixes up the order, why results.length lies about a half-full array, why one busy bank server blanks a whole dashboard, and why photos.map(upload) gets you an HTTP 429 error.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Programs with timers print times rounded to 100 ms, so the numbers are stable from run to run. Programs that use top-level await (await outside any function) work because Node 24 sees the await and runs the file as an ES module (the standard JavaScript module format).
First: what Promise.all does
- A promise is a box for a value that arrives later. It starts pending, then becomes fulfilled (someone called
resolve(value)) or rejected (someone calledreject(error)). Fulfilled or rejected = settled, and a promise settles only once. Promise.all(items)takes an array of promises (or plain values) and gives back one promise for an array of all the results, in the input order.- If any one of them rejects, the whole thing rejects at once, with that error.
Promise.alldoes not start anything. The work started when you called the functions;Promise.allonly waits.
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const cook = (dish, wait) => new Promise((resolve) => {
console.log(`start ${dish} at ${ms()}`);
setTimeout(() => resolve(dish), wait);
});
const orders = [cook("dal", 300), cook("roti", 100)];
console.log("Promise.all not called yet");
console.log(await Promise.all(orders), "at", ms());
console.log(await Promise.all([1, "two", cook("rice", 200)]));
start dal at 0
start roti at 0
Promise.all not called yet
[ 'dal', 'roti' ] at 300
start rice at 300
[ 1, 'two', 'rice' ]
Both dishes started before Promise.all was even called. The result keeps the input order (dal first, though roti was faster), and plain values like 1 and "two" are accepted as they are.
Q1: Write promiseAll(items)
Problem. Write promiseAll(items) without using the built-in Promise.all. It returns a promise for an array of all the results, in the order you asked. If any item rejects, reject at once with that error.
Real life: a thali (a plate with several bowls). You order dal, roti and rice from three counters. The dal takes 300 ms, the roti 100 ms, the rice 200 ms. The plate is served only when all three are ready, in the order you asked: dal, roti, rice.
Edge cases: things arrive in a different order than you asked; an empty array; plain values that aren't promises; one counter that fails.
The helper sleep(ms, v) waits ms milliseconds, then gives back the value v.
Attempt 1: push each value when it arrives
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
function promiseAll(list) {
return new Promise((resolve, reject) => {
const results = [];
list.forEach((p) => {
p.then((value) => {
results.push(value);
if (results.length === list.length) resolve(results);
}, reject);
});
});
}
const thali = await promiseAll([sleep(300, "dal"), sleep(100, "roti"), sleep(200, "rice")]);
console.log(thali);
[ 'roti', 'rice', 'dal' ]
The plate is full, but in the wrong order. push adds to the end, in the order things finish. Roti was fastest, so it went first. We have to remember where each one belongs.
p.then(onOk, onFail) takes two callbacks (functions you hand over to be called later): the first runs when p fulfils, the second when it rejects. Here the second one is simply reject.
Attempt 2: put each value at its own index
Take the index i (the position in the array, starting at 0) of each promise, and write results[i] = value instead of push. Same check on the length.
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
function promiseAll(list) {
return new Promise((resolve, reject) => {
const results = [];
list.forEach((p, i) => {
p.then((value) => {
results[i] = value;
if (results.length === list.length) resolve(results);
}, reject);
});
});
}
const thali = await promiseAll([sleep(300, "dal"), sleep(100, "roti"), sleep(200, "rice")]);
console.log(thali);
[ <1 empty item>, 'roti', 'rice' ]
It resolved early, with a hole where the dal should be. An array's length is its highest index plus one. When rice lands at index 2, the length jumps to 3, even though index 0 is still empty. Length counts places, not answers.
An array with holes is a sparse array; Node prints each hole as an empty item:
const plate = [];
plate[2] = "rice";
console.log(plate.length, plate);
console.log(0 in plate, plate[0]);
3 [ <2 empty items>, 'rice' ]
false undefined
0 in plate is false: index 0 doesn't exist at all (reading it gives undefined).
Real life: the thali has three bowls. Rice arrives first, in bowl three. Looking at the last bowl tells you nothing about the first one. So the waiter counts: one bowl filled, two, three, now serve. And if one counter shouts "roti burnt", the order is cancelled at once; you don't wait for the rice.
Fix: a done counter, an empty-array check, Promise.resolve
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const fail = (ms, msg) => sleep(ms).then(() => { throw new Error(msg); });
function promiseAll(items) {
return new Promise((resolve, reject) => {
const results = new Array(items.length);
let done = 0;
if (items.length === 0) return resolve(results);
items.forEach((item, i) => {
Promise.resolve(item).then((value) => {
results[i] = value;
done++;
if (done === items.length) resolve(results);
}, reject);
});
});
}
console.log(await promiseAll([sleep(300, "dal"), sleep(100, "roti"), sleep(200, "rice")]));
console.log(await promiseAll([sleep(100, "papad"), "pickle", 42]));
console.log(await promiseAll([]));
try {
await promiseAll([sleep(300, "dal"), fail(100, "roti burnt"), fail(200, "rice cold")]);
} catch (err) {
console.log("order failed:", err.message);
}
[ 'dal', 'roti', 'rice' ]
[ 'papad', 'pickle', 42 ]
[]
order failed: roti burnt
results[i] = valuekeeps the input order.donecounts answers, so we resolve only when every item has really arrived.if (items.length === 0) return resolve(results): with no items, nothencallback would ever run, so the promise would wait forever.Promise.resolve(item)turns a plain value into an already-fulfilled promise (and leaves a real promise as it is), so"pickle"and42work.- The first rejection wins.
roti burnt(at 100 ms) rejected the result;rice cold(at 200 ms) calledrejectagain, but a promise can settle only once, so laterresolveorrejectcalls do nothing. fail(ms, msg)waits, then throws insidethen, which turns into a rejected promise.
Complexity: O(n) time, one step per item, and O(n) space for the results.
Q2: Write allSettled(items)
Problem. Write allSettled(items). It waits for every promise, success or failure, and never rejects. For each item it gives an object: { status: "fulfilled", value } or { status: "rejected", reason }, in the input order.
Real life: a money app shows your balance from three banks. One bank's server is busy. You still want to see the other two.
Edge cases: everything fails; an empty array; the order must stay the same.
Attempt: Promise.all, then add them up
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const fail = (ms, msg) => sleep(ms).then(() => { throw new Error(msg); });
const banks = [sleep(100, 5200), fail(200, "SBI server busy"), sleep(300, 1800)];
try {
const balances = await Promise.all(banks);
console.log("total:", balances.reduce((a, b) => a + b, 0));
} catch (err) {
console.log("dashboard empty:", err.message);
}
dashboard empty: SBI server busy
Two good balances, thrown away. Promise.all is all or nothing: one rejection rejects the whole result, so we never see the values that did arrive.
Real life: a report card. If you missed one exam, should the school refuse to print the whole report? A fair report gives every subject a line ("Maths: 92", "Hindi: absent"), and the card is always printed. The parent reads it and decides.
Fix: turn every promise into one that can't fail
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const fail = (ms, msg) => sleep(ms).then(() => { throw new Error(msg); });
function allSettled(items) {
return Promise.all(items.map((item) =>
Promise.resolve(item).then(
(value) => ({ status: "fulfilled", value }),
(reason) => ({ status: "rejected", reason: reason.message }),
)));
}
const banks = [sleep(100, 5200), fail(200, "SBI server busy"), sleep(300, 1800)];
const report = await allSettled(banks);
console.log(report);
const ok = report.filter((r) => r.status === "fulfilled");
console.log("total of", ok.length, "banks:", ok.reduce((sum, r) => sum + r.value, 0));
console.log(await allSettled([]));
[
{ status: 'fulfilled', value: 5200 },
{ status: 'rejected', reason: 'SBI server busy' },
{ status: 'fulfilled', value: 1800 }
]
total of 2 banks: 7000
[]
then(onOk, onFail)turns success into{ status: "fulfilled", value }and failure into{ status: "rejected", reason }. Both callbacks return a normal object, so every mapped promise fulfils. Nothing can reject, soPromise.allis now safe to use.({ ... }): the round brackets make the arrow function return an object (without them,{would start a function body).- The built-in keeps the whole error object as the reason; we keep just its
message, so it prints neatly. []gives[]:Promise.all([])already resolves at once.
The "everything fails" edge case still gives a full report, never an error:
const fail = (ms, msg) => new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));
function allSettled(items) {
return Promise.all(items.map((item) =>
Promise.resolve(item).then(
(value) => ({ status: "fulfilled", value }),
(reason) => ({ status: "rejected", reason: reason.message }),
)));
}
const report = await allSettled([fail(100, "SBI busy"), fail(50, "HDFC busy")]);
console.log(report.map((r) => r.status + ": " + r.reason));
[ 'rejected: SBI busy', 'rejected: HDFC busy' ]
Still in input order: HDFC failed first, but SBI is listed first.
Complexity: O(n) time and O(n) space, one small object per item.
Q3: Run tasks with a concurrency limit
Problem. You upload an album of six photos. The server allows only two uploads at the same time; a third gets HTTP 429 ("Too Many Requests", the status code a server sends when you send too much at once). How many tasks are running at the same moment is called concurrency. Write runLimited(tasks, limit): it never runs more than limit tasks at once, and returns all results in order.
Edge cases: each task must be a function that starts the work when called (so nothing has started yet); a limit bigger than the list; an empty list.
Our fake server: upload counts how many are running. If two are already running, it throws a 429 error. Each upload takes 300 ms.
Attempt 1: Promise.all(photos.map(upload))
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
let running = 0;
async function upload(photo) {
if (running === 2) throw new Error(`429 too many uploads (${photo})`);
running++;
console.log(`start ${photo} at ${ms()}, running ${running}`);
await sleep(300);
running--;
return photo;
}
const photos = ["p1", "p2", "p3", "p4", "p5", "p6"];
try {
await Promise.all(photos.map(upload));
} catch (err) {
console.log("album failed:", err.message);
}
start p1 at 0, running 1
start p2 at 0, running 2
album failed: 429 too many uploads (p3)
map calls upload for all six photos straight away; Promise.all only waits. All six hit the server in the same moment: p1 and p2 got in, p3 got the 429 (and so did p4 to p6; Promise.all reports only the first).
Attempt 2: one at a time
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
let running = 0;
async function upload(photo) {
if (running === 2) throw new Error(`429 too many uploads (${photo})`);
running++;
console.log(`start ${photo} at ${ms()}, running ${running}`);
await sleep(300);
running--;
return photo;
}
const photos = ["p1", "p2", "p3", "p4", "p5", "p6"];
const done = [];
for (const photo of photos) done.push(await upload(photo));
console.log(done.length, "uploaded at", ms());
start p1 at 0, running 1
start p2 at 300, running 1
start p3 at 600, running 1
start p4 at 900, running 1
start p5 at 1200, running 1
start p6 at 1500, running 1
6 uploaded at 1800
No errors, but only one running at a time, starting every 300 ms: six uploads take 1800 ms. The server allows two, and we're using one. Correct, but half the speed.
Real life: a supermarket with six customers in one queue and two cashiers. Never more than two people are billed at once. When a cashier is free, she calls "next, please!" Nobody plans the order in advance: whoever is free takes the next customer. That is a worker pool: a fixed number of workers (small loops) that keep pulling the next task from a shared list.
Fix: a worker pool of size limit
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
let running = 0;
async function upload(photo) {
if (running === 2) throw new Error(`429 too many uploads (${photo})`);
running++;
console.log(`start ${photo} at ${ms()}, running ${running}`);
await sleep(300);
running--;
return photo;
}
const photos = ["p1", "p2", "p3", "p4", "p5", "p6"];
async function runLimited(tasks, limit) {
const results = new Array(tasks.length);
let next = 0;
async function worker() {
while (next < tasks.length) {
const i = next++;
results[i] = await tasks[i]();
}
}
const n = Math.min(limit, tasks.length);
await Promise.all(Array.from({ length: n }, worker));
return results;
}
const tasks = photos.map((p) => () => upload(p));
console.log(await runLimited(tasks, 2), "at", ms());
console.log(await runLimited([], 2));
start p1 at 0, running 1
start p2 at 0, running 2
start p3 at 300, running 2
start p4 at 300, running 2
start p5 at 600, running 2
start p6 at 600, running 2
[ 'p1', 'p2', 'p3', 'p4', 'p5', 'p6' ] at 900
[]
resultsand the sharednextindex belong torunLimited; every worker sees the same ones.- Each worker loops: while tasks are left, take the next index (
const i = next++),awaitthat task, store its result at its own index, so the results stay in order. Math.min(limit, tasks.length)workers: never more workers than tasks.Array.from({ length: n }, worker)callsworkern times and gives an array of n promises;Promise.allwaits until every worker has run out of tasks.- Tasks are functions (
() => upload(p)), so an upload starts only when a worker calls it. - p1 and p2 at 0, p3 and p4 at 300, p5 and p6 at 600: always two running, never three. All six are done at 900 ms, twice as fast as one at a time.
Why is next++ safe with two workers? JavaScript runs one piece of code at a time. Reading next and adding 1 happens with no await in between, so two workers can never take the same index.
Complexity: O(n) time, each task once (the wall-clock time is about n / limit task-lengths), and O(n) space for the results.
Going further
The built-in family: all, allSettled, any, race
The same three cab apps, given to each built-in:
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const fail = (ms, msg) => sleep(ms).then(() => { throw new Error(msg); });
const apps = () => [fail(100, "Ola: no cabs"), sleep(300, "Uber: 4 min"), sleep(200, "Rapido: 2 min")];
const show = async (name, p) => {
try { console.log(name, "->", await p); }
catch (err) { console.log(name, "-> rejected:", err.message); }
};
await show("all ", Promise.all(apps()));
await show("allSettled", Promise.allSettled(apps()).then((r) => r.map((x) => x.status)));
await show("any ", Promise.any(apps()));
await show("race ", Promise.race(apps()));
await show("any([]) ", Promise.any([]));
all -> rejected: Ola: no cabs
allSettled -> [ 'rejected', 'fulfilled', 'fulfilled' ]
any -> Rapido: 2 min
race -> rejected: Ola: no cabs
any([]) -> rejected: All promises were rejected
| Built-in | Fulfils with | Rejects when | [] gives |
|---|---|---|---|
Promise.all |
array of all values, input order | the first rejection | [] at once |
Promise.allSettled |
array of {status, value \| reason} |
never | [] at once |
Promise.any |
the first value that fulfils | all reject (with an AggregateError) |
rejects at once |
Promise.race |
whatever settles first (value or error) | the first to settle is a rejection | never settles |
An AggregateError is an Error with an extra errors array. Promise.any rejects with one (message All promises were rejected) when every item rejects, so you can see every reason; the "Your turn" solution below builds one by hand.
A pool that stops on the first error
In our runLimited, if one task fails, Promise.all rejects, but the other worker keeps pulling tasks. A stricter pool stops handing out new tasks after the first failure:
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
async function runLimitedStrict(tasks, limit) {
const results = new Array(tasks.length);
let next = 0;
let failed = false;
async function worker() {
while (!failed && next < tasks.length) {
const i = next++;
try {
results[i] = await tasks[i]();
} catch (err) {
failed = true;
throw err;
}
}
}
const n = Math.min(limit, tasks.length);
await Promise.all(Array.from({ length: n }, worker));
return results;
}
const upload = async (photo) => {
console.log(`start ${photo} at ${ms()}`);
await sleep(300);
if (photo === "p3") throw new Error(`${photo} is corrupted`);
return photo;
};
const tasks = ["p1", "p2", "p3", "p4", "p5", "p6"].map((p) => () => upload(p));
try {
await runLimitedStrict(tasks, 2);
} catch (err) {
console.log("stopped:", err.message, "at", ms());
}
await sleep(400);
console.log("nothing else started; ended at", ms());
start p1 at 0
start p2 at 0
start p3 at 300
start p4 at 300
stopped: p3 is corrupted at 600
nothing else started; ended at 1000
p4 had already started when p3 failed, so it finishes, but p5 and p6 never start. (A running task can't be stopped from outside; for that, pass an AbortSignal as in episode 21.)
Complexity summary
| Function | Time | Extra space |
|---|---|---|
promiseAll(items) |
O(n) | O(n): the results |
allSettled(items) |
O(n) | O(n): one object per item |
runLimited(tasks, k) |
O(n) work; wall-clock about n / k task-lengths | O(n) results + k workers |
Common mistakes (and the exact outputs)
| Mistake | Code | What you see | Why | Fix |
|---|---|---|---|---|
push the values |
results.push(value) |
[ 'roti', 'rice', 'dal' ] |
arrival order, not input order | results[i] = value |
Checking length |
if (results.length === n) |
[ <1 empty item>, 'roti', 'rice' ] |
length = highest index + 1 | a done counter |
| No empty-array check | promiseAll([]) |
Warning: Detected unsettled top-level await |
no then() ever runs |
resolve([]) at once |
p.then on a plain value |
promiseAll([1, 2]) with p.then |
TypeError: p.then is not a function |
plain values have no then |
Promise.resolve(item) |
Promise.all for a dashboard |
await Promise.all(banks) |
dashboard empty: SBI server busy |
all or nothing | allSettled |
| Starting every task | Promise.all(photos.map(upload)) |
album failed: 429 too many uploads (p3) |
map starts every task at once |
a worker pool of size limit |
| Passing promises, not functions | runLimited(photos.map(upload), 2) |
TypeError: tasks[i] is not a function |
the uploads already started | photos.map((p) => () => upload(p)) |
| A limit of 0 | runLimited(tasks, 0) |
[ <6 empty items> ] |
zero workers, nothing runs | check limit >= 1 |
The empty-array row, for real (Attempt 2's promiseAll):
function promiseAll(list) {
return new Promise((resolve, reject) => {
const results = [];
list.forEach((p, i) => {
p.then((value) => {
results[i] = value;
if (results.length === list.length) resolve(results);
}, reject);
});
});
}
console.log("waiting...");
console.log(await promiseAll([]));
waiting...
Warning: Detected unsettled top-level await at file:///home/user/main.js:13
console.log(await promiseAll([]));
^
The promise never settles, nothing else keeps Node busy, so Node exits with this warning (and exit code 13), and the last line never runs.
The other rows were run the same way: [1, 2] without Promise.resolve throws TypeError: p.then is not a function; runLimited(photos.map(upload), 2) throws TypeError: tasks[i] is not a function because map(upload) already called every upload (and got its 429s); and runLimited(tasks, 0) starts zero workers (Math.min(0, 6) is 0), so it uploads nothing and returns [ <6 empty items> ].
Mini project: a PNR status checker
A railway app checks seven PNR numbers (ticket numbers). The API allows three requests at once, and one PNR doesn't exist. Combine Q2 and Q3: a worker pool with a limit of 3, where every task is settled first, so one bad PNR can't stop the others.
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
let running = 0;
let peak = 0;
async function checkPnr(pnr) {
running++;
peak = Math.max(peak, running);
try {
await sleep(pnr.endsWith("7") ? 400 : 200);
if (pnr.startsWith("0")) throw new Error(`PNR ${pnr} not found`);
return `PNR ${pnr}: confirmed`;
} finally {
running--;
}
}
async function runLimited(tasks, limit) {
const results = new Array(tasks.length);
let next = 0;
async function worker() {
while (next < tasks.length) {
const i = next++;
results[i] = await tasks[i]();
}
}
const n = Math.min(limit, tasks.length);
await Promise.all(Array.from({ length: n }, worker));
return results;
}
const settled = (task) => () => task().then(
(value) => ({ status: "fulfilled", value }),
(err) => ({ status: "rejected", reason: err.message }),
);
const pnrs = ["4521", "8807", "0193", "6624", "1177", "9340", "2286"];
const report = await runLimited(pnrs.map((p) => settled(() => checkPnr(p))), 3);
for (const r of report) console.log(r.status === "fulfilled" ? "ok " + r.value : "fail " + r.reason);
console.log(`done at ${ms()}, at most ${peak} at once`);
ok PNR 4521: confirmed
ok PNR 8807: confirmed
fail PNR 0193 not found
ok PNR 6624: confirmed
ok PNR 1177: confirmed
ok PNR 9340: confirmed
ok PNR 2286: confirmed
done at 600, at most 3 at once
settled(task)wraps a task so its promise always fulfils with a status object (the same trick as Q2), so the pool never rejects.try...finallylowersrunningwhether the check succeeds or fails.- The report is in input order, even though the slow PNRs (ending in 7) finished late. Seven checks at 200 to 400 ms each, three at a time, finish in 600 ms instead of the 1800 ms one by one would take.
Your turn: write promiseAny(items) (solution)
Problem. promiseAny(items) resolves with the first success and ignores failures. Only if all of them fail, reject with AggregateError(errors, "All promises were rejected"), with the errors in input order. Real life: you ask three cab apps, and book whichever one finds a car first.
Hint: it's the mirror image of promiseAll: count failures instead of successes.
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const fail = (ms, msg) => sleep(ms).then(() => { throw new Error(msg); });
function promiseAny(items) {
return new Promise((resolve, reject) => {
const errors = new Array(items.length);
let failed = 0;
if (items.length === 0) return reject(new AggregateError(errors, "All promises were rejected"));
items.forEach((item, i) => {
Promise.resolve(item).then(resolve, (err) => {
errors[i] = err;
failed++;
if (failed === items.length) reject(new AggregateError(errors, "All promises were rejected"));
});
});
});
}
console.log(await promiseAny([fail(100, "Ola: no cabs"), sleep(300, "Uber: 4 min"), sleep(200, "Rapido: 2 min")]));
console.log(await promiseAny([fail(50, "offline"), "cached cab"]));
for (const input of [[fail(200, "Ola: no cabs"), fail(100, "Uber: no cabs")], []]) {
try {
await promiseAny(input);
} catch (err) {
console.log(err.constructor.name, "|", err.message, "|", err.errors.map((e) => e.message));
}
}
Rapido: 2 min
cached cab
AggregateError | All promises were rejected | [ 'Ola: no cabs', 'Uber: no cabs' ]
AggregateError | All promises were rejected | []
- Success: the first
resolvewins; later ones do nothing (a promise settles once). Rapido (200 ms) beat Uber (300 ms); Ola's failure was ignored. - Failure:
errors[i] = errkeeps the input order (Uber failed first but is listed second), andfailedcounts failures, exactly likedonein Q1. []rejects at once with an emptyerrorsarray, just like the built-inPromise.any([]).
Complexity: O(n) time and O(n) space for the errors.
Practice questions (with solutions)
1. Write promiseRace(items): settle like whichever item settles first.
Solution
const sleep = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const fail = (ms, msg) => sleep(ms).then(() => { throw new Error(msg); });
function promiseRace(items) {
return new Promise((resolve, reject) => {
for (const item of items) Promise.resolve(item).then(resolve, reject);
});
}
console.log(await promiseRace([sleep(300, "bus"), sleep(100, "auto")]));
try {
await promiseRace([sleep(300, "bus"), fail(100, "auto broke down")]);
} catch (err) {
console.log("race lost:", err.message);
}
console.log(await promiseRace([sleep(100, "metro"), "walk"]));
auto
race lost: auto broke down
walk
Every item gets the same resolve and reject; the first to call one settles the promise and the rest are ignored. No counter is needed. promiseRace([]) never settles, like the built-in.
2. Predict the output.
const a = ["dal"];
a[3] = "rice";
console.log(a.length, a);
let visits = 0;
a.forEach(() => visits++);
console.log(visits, a.filter(() => true).length);
console.log(await Promise.all(a));
Answer
4 [ 'dal', <2 empty items>, 'rice' ]
2 2
[ 'dal', undefined, undefined, 'rice' ]
length is 4 (highest index 3, plus one), with two empty items. forEach and filter skip holes, so they see only 2 items. But Promise.all reads every index from 0 to length − 1, and a hole reads as undefined, so it gives 4 results.
3. Batches vs a pool. A common answer splits the tasks into groups of limit and runs Promise.all on each group. Why is that slower than a worker pool when tasks take different times?
Solution
const t0 = Date.now();
const ms = () => Math.round((Date.now() - t0) / 100) * 100;
const sleep = (wait) => new Promise((r) => setTimeout(r, wait));
const times = [500, 100, 100, 100, 100, 100];
const tasks = times.map((t) => () => sleep(t));
async function inBatches(tasks, limit) {
for (let i = 0; i < tasks.length; i += limit) {
await Promise.all(tasks.slice(i, i + limit).map((task) => task()));
}
}
async function runLimited(tasks, limit) {
let next = 0;
const worker = async () => { while (next < tasks.length) await tasks[next++](); };
await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, worker));
}
let start = ms();
await inBatches(tasks, 2);
console.log("batches took", ms() - start);
start = ms();
await runLimited(tasks, 2);
console.log("pool took ", ms() - start);
batches took 700
pool took 500
A batch waits for its slowest task before the next batch starts: in the first batch the 500 ms task keeps one slot busy, and the other slot sits idle for 400 ms. In the pool, the free worker keeps pulling tasks while the slow one runs: it does all five short tasks (500 ms in total), and both finish together.
4. Is this worker still safe? A candidate splits const i = next++ into const i = next;, then await sleep(10);, then next++;. What goes wrong?
Answer
There is now an await between reading next and increasing it. While worker A is paused, worker B reads the same next, so both take index 0 and task 0 runs twice (that is what happened when we ran it with two workers and four tasks: A took index 0, B took index 0). Which index each worker gets from then on depends on timing. Read and increase in one step, const i = next++, with no await in between.
5. Make runLimited safe for a bad limit. Without a check, runLimited(tasks, 0) silently returns [ <6 empty items> ]. Fix it in one line.
Answer
Add if (!(limit >= 1)) throw new RangeError(`limit must be at least 1, got ${limit}`); at the top. !(limit >= 1) also catches NaN (every comparison with NaN is false), and a RangeError is the built-in error for "a number outside the allowed range". A default of limit = Infinity means "no limit", since Math.min(Infinity, n) is n.
Quick quiz
const a = [];
a[4] = "chai";
console.log(a.length);
const r = await Promise.all([1, Promise.resolve(2), "3"]);
console.log(r);
A) 1, then [ 1, 2, '3' ] B) 5, then [ 1, 2, '3' ] C) 5, then a TypeError D) 1, then [ 1, 2, 3 ]
Answer
5
[ 1, 2, '3' ]
B. Setting index 4 makes the length 5 (highest index + 1), with 4 empty items. Promise.all accepts plain values: each one is wrapped with Promise.resolve, and '3' stays a string.
Interview questions
- Write
Promise.allfrom scratch. A new promise;results[i] = value; adonecounter;resolve([])at once for an empty input;Promise.resolve(item)for plain values;rejecton the first error. - Why not
results.push? It stores values in arrival order, not input order. - Why not check
results.length? Setting a high index first makeslengthjump (highest index + 1) while lower indexes are still empty. - Does
Promise.allrun the promises in parallel? It doesn't run anything; the work started when the functions were called. It only waits. (JavaScript itself runs one piece of code at a time; the waiting overlaps.) - What happens to the other promises when
Promise.allrejects? They keep running; their results are ignored. Nothing is cancelled. Promise.allvsPromise.allSettled?allis all or nothing;allSettlednever rejects and reports each result with a status.Promise.anyvsPromise.race?anywaits for the first success (rejects withAggregateErroronly if all fail);racetakes the first to settle, even a failure.- How do you limit concurrency? Pass functions, not promises, and start
limitworkers that pull the next index from a shared counter; or use a queue-based limiter likep-limit. - Why is
next++safe across workers? JavaScript runs one piece of code at a time, and there is noawaitbetween reading and increasingnext. - Why is a worker pool better than batches? A batch waits for its slowest task; a pool keeps every slot busy.
Glossary
| Term | Meaning |
|---|---|
| Promise | A box for a value that arrives later |
| Pending / fulfilled / rejected | The three states of a promise: waiting / succeeded with a value / failed with an error |
| Settle / settled | Become fulfilled or rejected; a promise settles only once |
resolve(value) |
The function that fulfils a new promise with value |
reject(error) |
The function that rejects a new promise with error |
| Reason | The error a promise was rejected with |
| Callback | A function you hand over to be called later (e.g. the functions passed to then) |
then(onOk, onFail) |
Run onOk when a promise fulfils, onFail when it rejects; returns a new promise |
Promise.resolve(x) |
A promise fulfilled with x (or x itself if it is already a promise) |
Promise.all |
Waits for all; fulfils with every value in input order; rejects on the first rejection |
Promise.allSettled |
Waits for all; never rejects; one {status, value \| reason} object per item |
Promise.any |
Fulfils with the first success; rejects with an AggregateError if all fail |
Promise.race |
Settles like the first item to settle |
AggregateError |
An error with an errors array holding many errors |
| Index | The position of an item in an array, starting at 0 |
length |
An array's highest index plus one |
| Sparse array | An array with holes (indexes that don't exist) |
| Empty item | How Node prints a hole in a sparse array |
| Input order / arrival order | The order you asked for / the order things finished |
| Task | Here: a function that starts some async work when called and returns a promise |
| Concurrency | How many tasks are running at the same moment |
| Concurrency limit | The most tasks allowed to run at once |
| Worker | A small async loop that keeps taking the next task |
| Worker pool | A fixed number of workers sharing one list of tasks |
| Queue | A list served first-in, first-out |
| Batch | A fixed group of tasks run together before the next group starts |
| HTTP 429 | "Too Many Requests": a server's answer when you send more than it allows |
p-limit |
A popular npm package that limits concurrency (we wrote our own) |
| Async function | A function marked async; it always returns a promise |
await |
Pause the async function until a promise settles |
Top-level await |
await outside any function; works in ES modules |
| ES module | The standard JavaScript module format (import/export) |
Array.from({ length: n }, fn) |
An array of n items, each made by calling fn |
try...finally |
finally runs whether the try block succeeded or threw |
RangeError |
The built-in error for a number outside the allowed range |
| Exit code | A number a program returns when it ends; 0 means success |
| Big-O | How the work grows with the input size |
Summary
Promise.allonly waits; calling the functions starts the work. Write it withresults[i] = value(input order), adonecounter (notlength, which is the highest index + 1),resolve([])at once for an empty input,Promise.resolvefor plain values, andrejecton the first error (a promise settles once).allSettled=then(onOk, onFail)that turns every result into a status object, thenPromise.all, which now can't fail.photos.map(upload)starts everything at once. To limit concurrency, pass functions and startlimitworkers that pullnext++from a shared index: alwayslimitrunning, results in order.Promise.anyis the mirror image ofPromise.all: count failures, and reject with anAggregateError.- Next episode: event loop output questions:
setTimeout, promises,async/await,queueMicrotaskandprocess.nextTickin one program; predict the order, then run it.