Write runInSeries(tasks). tasks is an array of functions; each returns a promise or a plain value. Call them one at a time: start each task only after the previous one has finished. Return a promise that fulfills with their results, in order.
If a task fails (its promise rejects, or it throws), reject with that error and don't start the tasks after it. With no tasks, fulfill with [].
const [user, posts] = await runInSeries([
() => fetchJson("/api/user"),
() => fetchJson("/api/posts"), // starts only once the user has arrived
]);
const clock = useFakeTimers();
const after = (ms, value) => () => new Promise((resolve) => setTimeout(resolve, ms, value));
let result;
runInSeries([after(300, "a"), after(100, "b"), after(200, "c")]).then((value) => {
result = value;
});
await clock.tickAsync(600);
expect(result).toEqual(["a", "b", "c"]);
const clock = useFakeTimers();
const start = clock.now();
const startedAt = [];
const task = (value) => () => {
startedAt.push(clock.now() - start);
return new Promise((resolve) => setTimeout(resolve, 100, value));
};
runInSeries([task(1), task(2), task(3)]);
await clock.tickAsync(300);
expect(startedAt).toEqual([0, 100, 200]);
await expect(runInSeries([() => 1, () => "two", () => null])).resolves.toEqual([1, "two", null]);
const clock = useFakeTimers();
const error = new Error("offline");
let reason;
runInSeries([
() => Promise.resolve(1),
() => new Promise((_, reject) => setTimeout(reject, 100, error)),
() => 3,
]).catch((e) => {
reason = e;
});
await clock.tickAsync(100);
expect(reason).toBe(error);
const last = spy(() => "never");
await runInSeries([() => 1, () => Promise.reject(new Error("offline")), last]).catch(() => {}); // it rejects; this test only checks what ran
await flush();
expect(last).not.toHaveBeenCalled();
const error = new Error("bad task");
const failing = () => {
throw error;
};
await expect(runInSeries([() => 1, failing])).rejects.toBe(error);
await expect(runInSeries([])).resolves.toEqual([]);
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 Run async tasks in series. 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.