The tea shop's reviews page scores every review, and with thousands of them one loop is a long task: until it ends, the page can't respond to a tap or paint anything. Write processInChunks(items, work, options), an async function that calls work(item, index) for every item, in order, and resolves with an array of what each call returned.
Keep each piece of work short. Before each item, if options.budget ms (50 when it isn't given) or more have passed since you started or last yielded, yield to the browser first, then start timing again. Read the time with performance.now().
Yield with scheduler.yield() where the browser has it, and with a 0 ms setTimeout where it doesn't: some browsers have no scheduler at all, and some have scheduler.postTask() but not scheduler.yield(). If work throws, the promise rejects with that error, and no later item runs.
const scores = await processInChunks(reviews, (review) => scoreReview(review.text));
// The scores come back in the reviews' order. Every 50 ms or so the loop stops,
// so the browser can handle a tap and paint, and then it carries on.
const clock = useFakeTimers();
const seen = [];
const done = processInChunks(["green", "black", "oolong"], (tea, index) => {
clock.spend(5);
seen.push(index + ":" + tea);
return tea.toUpperCase();
});
await clock.runAllAsync();
expect(await done).toEqual(["GREEN", "BLACK", "OOLONG"]);
expect(seen).toEqual(["0:green", "1:black", "2:oolong"]);
const clock = useFakeTimers();
const done = [];
const finished = processInChunks([1, 2, 3, 4, 5], (n) => {
clock.spend(20);
done.push(n);
});
// 60 ms of work: it yields before the fourth item.
expect(done).toEqual([1, 2, 3]);
await clock.runAllAsync();
await finished;
expect(done).toEqual([1, 2, 3, 4, 5]);
const clock = useFakeTimers();
const pieces = [[]];
const realYield = scheduler.yield.bind(scheduler);
scheduler.yield = () => {
pieces.push([]);
return realYield();
};
const finished = processInChunks([1, 2, 3, 4, 5, 6, 7], (n) => {
clock.spend(20);
pieces[pieces.length - 1].push(n);
});
await clock.runAllAsync();
await finished;
expect(pieces).toEqual([[1, 2, 3], [4, 5, 6], [7]]);
const clock = useFakeTimers();
let yields = 0;
const realYield = scheduler.yield.bind(scheduler);
scheduler.yield = () => {
yields += 1;
return realYield();
};
const results = await processInChunks([1, 2, 3, 4], (n) => {
clock.spend(10);
return n * 2;
});
expect(results).toEqual([2, 4, 6, 8]);
expect(yields).toBe(0);
const clock = useFakeTimers();
const used = { yield: 0, timeout: 0 };
const realYield = scheduler.yield.bind(scheduler);
scheduler.yield = () => {
used.yield += 1;
return realYield();
};
const realTimeout = setTimeout;
globalThis.setTimeout = (fn, ms, ...rest) => {
used.timeout += 1;
return realTimeout(fn, ms, ...rest);
};
const finished = processInChunks([1, 2, 3], () => clock.spend(60));
await clock.runAllAsync();
await finished;
expect(used.yield).toBeGreaterThan(0);
expect(used.timeout).toBe(0);
const clock = useFakeTimers({ scheduler: false });
const delays = [];
const realTimeout = setTimeout;
globalThis.setTimeout = (fn, ms, ...rest) => {
delays.push(Number(ms) || 0);
return realTimeout(fn, ms, ...rest);
};
const done = [];
const finished = processInChunks([1, 2, 3], (n) => {
clock.spend(60);
done.push(n);
});
expect(done).toEqual([1]);
await clock.runAllAsync();
await finished;
expect(done).toEqual([1, 2, 3]);
expect(delays.length).toBeGreaterThan(0);
expect(delays.every((ms) => ms === 0)).toBe(true);
const clock = useFakeTimers();
globalThis.scheduler = { postTask: scheduler.postTask.bind(scheduler) };
let timeouts = 0;
const realTimeout = setTimeout;
globalThis.setTimeout = (fn, ms, ...rest) => {
timeouts += 1;
return realTimeout(fn, ms, ...rest);
};
const finished = processInChunks([1, 2, 3], () => clock.spend(60));
await clock.runAllAsync();
expect((await finished).length).toBe(3);
expect(timeouts).toBeGreaterThan(0);
const clock = useFakeTimers();
const pieces = [[]];
const realYield = scheduler.yield.bind(scheduler);
scheduler.yield = () => {
pieces.push([]);
return realYield();
};
const finished = processInChunks([1, 2, 3, 4, 5], (n) => {
clock.spend(30);
pieces[pieces.length - 1].push(n);
}, { budget: 100 });
await clock.runAllAsync();
await finished;
expect(pieces).toEqual([[1, 2, 3, 4], [5]]);
const clock = useFakeTimers();
const done = [];
const outcome = processInChunks([1, 2, 3, 4], (n) => {
clock.spend(30);
if (n === 3) throw new Error("This review has no text");
done.push(n);
}).then(
() => "resolved",
(error) => error.message,
);
await clock.runAllAsync();
expect(await outcome).toBe("This review has no text");
expect(done).toEqual([1, 2]);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Process in chunks. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.