Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions __tests__/run-tasks-with-limit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,46 @@ describe("runTasksWithLimit", () => {
runTasksWithLimit([async () => 1, async () => Promise.reject(failure)], 2)
).rejects.toBe(failure);
});

test("stops scheduling new tasks after the first rejection", async () => {
const failure = new Error("task failed");
const started: number[] = [];
let markSecondStarted!: () => void;
let releaseSecond!: () => void;
const secondStarted = new Promise<void>((resolve) => {
markSecondStarted = resolve;
});
const secondRelease = new Promise<void>((resolve) => {
releaseSecond = resolve;
});
const tasks = [
async () => {
started.push(0);
await secondStarted;
throw failure;
},
async () => {
started.push(1);
markSecondStarted();
await secondRelease;
return 1;
},
async () => {
started.push(2);
return 2;
},
async () => {
started.push(3);
return 3;
},
];

const run = runTasksWithLimit(tasks, 2);

await expect(run).rejects.toBe(failure);
releaseSecond();
await new Promise<void>((resolve) => setImmediate(resolve));

expect(started).toEqual([0, 1]);
});
});
11 changes: 9 additions & 2 deletions src/utils/run-tasks-with-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,18 @@ export async function runTasksWithLimit<T>(
): Promise<T[]> {
const results: T[] = [];
let index = 0;
let failed = false;

async function runNext(): Promise<void> {
while (index < tasks.length) {
while (!failed && index < tasks.length) {
const currentIndex = index++;
results[currentIndex] = await tasks[currentIndex]();

try {
results[currentIndex] = await tasks[currentIndex]();
} catch (error) {
failed = true;
throw error;
}
}
}

Expand Down