After its first paint, the tea shop's menu page fetches a lot: the details of the teas on screen, then reviews and photos for further down. Browsers order their own requests, but every fetch() a script makes starts at once and competes for the same bandwidth. Write createFetchQueue(limit), which returns { request(url, options) } and runs at most limit fetches at a time, the important ones first.
request(url, { priority }) takes a priority of "high" or "low" ("low" when it isn't given) and returns a promise that settles as fetch(url, { priority }) does: with its response, or with its error. Pass the priority on: fetch's priority option tells the browser how to order the request among the page's others, as the fetchpriority attribute does on an element.
When fewer than limit fetches are running, start the new one at once, in the same call. Otherwise it waits. Each time a fetch settles, start the next: the high request that has waited longest, or, when no high one is waiting, the low one that has waited longest. A running fetch is never stopped for a newer one. A fetch counts as running until its promise settles, which is when the response's headers arrive or the fetch fails, and a failure frees its place just as a response does. A limit that isn't a whole number of 1 or more is a RangeError.
The JavaScript problem Map with a concurrency limit (map-with-concurrency-limit) runs one list of calls with a limit. This is a queue that keeps taking requests as the page makes them, and orders them by priority.
const queue = createFetchQueue(2);
queue.request("/api/teas/oolong", { priority: "high" }); // starts at once
queue.request("/api/reviews?page=2"); // starts at once: there's still room
queue.request("/api/reviews?page=3"); // waits
queue.request("/api/teas/mint", { priority: "high" }); // waits, but goes before page 3
const clock = useFakeTimers();
const network = useFetch(() => ({ body: {}, delay: 100 }));
const queue = createFetchQueue(2);
for (const tea of ["green", "mint", "oolong", "black"]) queue.request("/api/teas/" + tea);
expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/green", "/api/teas/mint"]);
await clock.tickAsync(99);
expect(network.calls).toHaveLength(2);
const clock = useFakeTimers();
const delays = { "/api/teas/green": 100, "/api/teas/mint": 300 };
const network = useFetch((url) => ({ body: { url }, delay: delays[url] ?? 50 }));
const queue = createFetchQueue(2);
for (const tea of ["green", "mint", "oolong", "black"]) queue.request("/api/teas/" + tea);
await clock.tickAsync(100);
expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/green", "/api/teas/mint", "/api/teas/oolong"]);
await clock.tickAsync(50);
expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/green", "/api/teas/mint", "/api/teas/oolong", "/api/teas/black"]);
const clock = useFakeTimers();
const network = useFetch(() => ({ body: {}, delay: 100 }));
const queue = createFetchQueue(1);
queue.request("/api/reviews?page=1");
queue.request("/api/reviews?page=2");
queue.request("/api/teas/oolong", { priority: "high" });
queue.request("/api/reviews?page=3", { priority: "low" });
queue.request("/api/teas/mint", { priority: "high" });
for (let step = 0; step < 5; step++) await clock.tickAsync(100);
expect(network.calls.map((call) => call.url)).toEqual([
"/api/reviews?page=1",
"/api/teas/oolong",
"/api/teas/mint",
"/api/reviews?page=2",
"/api/reviews?page=3",
]);
const clock = useFakeTimers();
const network = useFetch(() => ({ body: {}, delay: 100 }));
const queue = createFetchQueue(1);
const reviews = queue.request("/api/reviews?page=2");
queue.request("/api/teas/oolong", { priority: "high" });
expect(network.calls.map((call) => call.url)).toEqual(["/api/reviews?page=2"]);
await clock.tickAsync(100);
expect((await reviews).ok).toBe(true);
expect(network.calls.map((call) => call.url)).toEqual(["/api/reviews?page=2", "/api/teas/oolong"]);
const network = useFetch(() => ({ body: {} }));
const queue = createFetchQueue(4);
queue.request("/api/teas/oolong", { priority: "high" });
queue.request("/api/reviews?page=2", { priority: "low" });
queue.request("/api/photos/oolong");
expect(network.calls.map((call) => call.priority)).toEqual(["high", "low", "low"]);
const clock = useFakeTimers();
const network = useFetch((url) => {
if (url === "/api/teas/broken") throw new TypeError("Failed to fetch");
return { body: { url }, delay: 100 };
});
const queue = createFetchQueue(1);
const broken = queue.request("/api/teas/broken", { priority: "high" });
const oolong = queue.request("/api/teas/oolong");
await expect(broken).rejects.toThrow("Failed to fetch");
await clock.tickAsync(100);
expect(await (await oolong).json()).toEqual({ url: "/api/teas/oolong" });
expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/broken", "/api/teas/oolong"]);
const clock = useFakeTimers();
const network = useFetch(() => ({ body: {}, delay: 100 }));
const queue = createFetchQueue(1);
queue.request("/api/teas/green");
await clock.tickAsync(100);
queue.request("/api/teas/mint");
expect(network.calls.map((call) => call.url)).toEqual(["/api/teas/green", "/api/teas/mint"]);
expect(() => createFetchQueue(0)).toThrow(RangeError);
expect(() => createFetchQueue(1.5)).toThrow(RangeError);
expect(() => createFetchQueue("2")).toThrow(RangeError);
expect(() => createFetchQueue(1)).not.toThrow();
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 A fetch queue with priorities. 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.