← All tasksJavaScript · Senior
runWithLimit: promise pool
Write a function runWithLimit(tasks, limit). tasks is an array of functions that each return a promise. Run them all, but with no more than limit running at once: as soon as one finishes, the next one starts.
Return a promise with the results in the order of tasks. If a task fails, the overall promise rejects with that error and no new tasks are started.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (6)
let active = 0; let peak = 0; const task = (v) => async () => { active++; peak = Math.max(peak, active); await wait(20); active--; return v; }; const result = await runWithLimit([1, 2, 3, 4, 5].map(task), 2); expect(result).toEqual([1, 2, 3, 4, 5]); expect(peak).toBe(2);
const order = []; const task = (v, ms) => async () => { await wait(ms); order.push(v); return v; }; const result = await runWithLimit([task('a', 60), task('b', 10), task('c', 10)], 2); expect(result).toEqual(['a', 'b', 'c']); expect(order).toEqual(['b', 'c', 'a']);
expect(await runWithLimit([], 3)).toEqual([]);
const error = new Error('fail'); await expect(runWithLimit([async () => 1, async () => { throw error; }], 2)).rejects.toBe(error);
const started = fn(); const tasks = [1, 2, 3].map((v) => () => { started(v); return wait(30).then(() => v); }); const promise = runWithLimit(tasks, 1); await wait(10); expect(started).toHaveBeenCalledTimes(1); expect(await promise).toEqual([1, 2, 3]); expect(started).toHaveBeenCalledTimes(3);
const started = Date.now(); await runWithLimit([1, 2, 3, 4].map(() => () => wait(40)), 4); expect(Date.now() - started < 120).toBe(true);