{"id":"6b093dddbd4755deb67ee052","slug":"async-task-pool","title":"Pula zadań asynchronicznych z limitem","summary":"Uruchamiamy tysiące asynchronicznych zadań, ale nie więcej niż N naraz – jak przy pobieraniu plików czy wywołaniach API z limitem. Obietnice, kolejność wyników i zatrzymanie przy pierwszym błędzie.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":[],"techs":["typescript","javascript"],"tags":["javascript","node","promises","async","concurrency","event-loop"],"languages":[{"lang":"typescript","runner":"browser","starter":"/**\n * Runs task functions with at most `limit` in flight; resolves to results in task order.\n * Rejects with the first error (and starts no new tasks), RangeError for an invalid limit.\n */\nfunction runWithLimit<T>(tasks: Array<() => T | Promise<T>>, limit: number): Promise<T[]> {\n  // TODO\n  return Promise.reject(new Error('Not implemented'));\n}\n","testCount":9,"tests":"function deferred() {\n  let resolve, reject;\n  const promise = new Promise((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return { promise, resolve, reject };\n}\n\nconst tick = () => new Promise((resolve) => setTimeout(resolve, 0));\n\nfunction controlledTasks(n) {\n  const started = [];\n  const controls = Array.from({ length: n }, () => deferred());\n  const tasks = controls.map((d, i) => () => {\n    started.push(i);\n    return d.promise;\n  });\n  return { tasks, controls, started };\n}\n\ntest('results come in task order, not completion order', async () => {\n  const { tasks, controls } = controlledTasks(3);\n  const pool = runWithLimit(tasks, 3);\n  controls[2].resolve('c');\n  controls[0].resolve('a');\n  controls[1].resolve('b');\n  expect(await pool).toEqual(['a', 'b', 'c']);\n});\n\ntest('never more than `limit` tasks in flight', async () => {\n  let running = 0;\n  let maxRunning = 0;\n  const tasks = Array.from({ length: 20 }, (_, i) => async () => {\n    running++;\n    maxRunning = Math.max(maxRunning, running);\n    await new Promise((resolve) => setTimeout(resolve, (i * 7) % 5));\n    running--;\n    return i * i;\n  });\n  const results = await runWithLimit(tasks, 3);\n  expect(maxRunning).toBe(3);\n  expect(results).toEqual(Array.from({ length: 20 }, (_, i) => i * i));\n});\n\ntest('the next task starts as soon as a slot frees up', async () => {\n  const { tasks, controls, started } = controlledTasks(4);\n  const pool = runWithLimit(tasks, 2);\n  await tick();\n  expect(started).toEqual([0, 1]);\n  controls[1].resolve('B');\n  await tick();\n  expect(started).toEqual([0, 1, 2]);\n  controls[2].resolve('C');\n  await tick();\n  expect(started).toEqual([0, 1, 2, 3]);\n  controls[3].resolve('D');\n  controls[0].resolve('A');\n  expect(await pool).toEqual(['A', 'B', 'C', 'D']);\n});\n\ntest('empty task list and a limit larger than the list', async () => {\n  expect(await runWithLimit([], 5)).toEqual([]);\n  const { tasks, controls, started } = controlledTasks(3);\n  const pool = runWithLimit(tasks, 10);\n  await tick();\n  expect(started).toEqual([0, 1, 2]);\n  controls.forEach((d, i) => d.resolve(i));\n  expect(await pool).toEqual([0, 1, 2]);\n});\n\ntest('plain values and synchronous task functions work', async () => {\n  expect(await runWithLimit([() => 1, () => Promise.resolve(2), async () => 3], 2)).toEqual([1, 2, 3]);\n});\n\ntest('the first error rejects the pool and stops new tasks', async () => {\n  const { tasks, controls, started } = controlledTasks(4);\n  const pool = runWithLimit(tasks, 2);\n  await tick();\n  const boom = new Error('boom');\n  controls[1].reject(boom);\n  let caught = null;\n  try {\n    await pool;\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(boom);\n  controls[0].resolve('late');\n  await tick();\n  expect(started).toEqual([0, 1]);\n});\n\ntest('a task function that throws synchronously rejects the pool', async () => {\n  const error = new TypeError('bad task');\n  let caught = null;\n  try {\n    await runWithLimit([() => 1, () => { throw error; }, () => 3], 1);\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(error);\n});\n\ntest('invalid limit gives RangeError', async () => {\n  for (const limit of [0, -1, 1.5, NaN]) {\n    let caught = null;\n    try {\n      await runWithLimit([() => 1], limit);\n    } catch (e) {\n      caught = e;\n    }\n    expect(caught).toBeInstanceOf(RangeError);\n  }\n});\n\ntest('performance: 20 000 tasks with limit 50', async () => {\n  let running = 0;\n  let maxRunning = 0;\n  const tasks = Array.from({ length: 20000 }, (_, i) => () => {\n    running++;\n    maxRunning = Math.max(maxRunning, running);\n    return Promise.resolve(i).then((v) => {\n      running--;\n      return v;\n    });\n  });\n  const results = await runWithLimit(tasks, 50);\n  expect(results).toHaveLength(20000);\n  expect(results[19999]).toBe(19999);\n  expect(results.reduce((a, b) => a + b, 0)).toBe((19999 * 20000) / 2);\n  expect(maxRunning).toBeLessThanOrEqual(50);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Runs task functions with at most `limit` in flight; resolves to results in task order.\n * Rejects with the first error (and starts no new tasks), RangeError for an invalid limit.\n * @param {Array<() => any>} tasks\n * @param {number} limit\n * @returns {Promise<any[]>}\n */\nfunction runWithLimit(tasks, limit) {\n  // TODO\n  return Promise.reject(new Error('Not implemented'));\n}\n","testCount":9,"tests":"function deferred() {\n  let resolve, reject;\n  const promise = new Promise((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  return { promise, resolve, reject };\n}\n\nconst tick = () => new Promise((resolve) => setTimeout(resolve, 0));\n\nfunction controlledTasks(n) {\n  const started = [];\n  const controls = Array.from({ length: n }, () => deferred());\n  const tasks = controls.map((d, i) => () => {\n    started.push(i);\n    return d.promise;\n  });\n  return { tasks, controls, started };\n}\n\ntest('results come in task order, not completion order', async () => {\n  const { tasks, controls } = controlledTasks(3);\n  const pool = runWithLimit(tasks, 3);\n  controls[2].resolve('c');\n  controls[0].resolve('a');\n  controls[1].resolve('b');\n  expect(await pool).toEqual(['a', 'b', 'c']);\n});\n\ntest('never more than `limit` tasks in flight', async () => {\n  let running = 0;\n  let maxRunning = 0;\n  const tasks = Array.from({ length: 20 }, (_, i) => async () => {\n    running++;\n    maxRunning = Math.max(maxRunning, running);\n    await new Promise((resolve) => setTimeout(resolve, (i * 7) % 5));\n    running--;\n    return i * i;\n  });\n  const results = await runWithLimit(tasks, 3);\n  expect(maxRunning).toBe(3);\n  expect(results).toEqual(Array.from({ length: 20 }, (_, i) => i * i));\n});\n\ntest('the next task starts as soon as a slot frees up', async () => {\n  const { tasks, controls, started } = controlledTasks(4);\n  const pool = runWithLimit(tasks, 2);\n  await tick();\n  expect(started).toEqual([0, 1]);\n  controls[1].resolve('B');\n  await tick();\n  expect(started).toEqual([0, 1, 2]);\n  controls[2].resolve('C');\n  await tick();\n  expect(started).toEqual([0, 1, 2, 3]);\n  controls[3].resolve('D');\n  controls[0].resolve('A');\n  expect(await pool).toEqual(['A', 'B', 'C', 'D']);\n});\n\ntest('empty task list and a limit larger than the list', async () => {\n  expect(await runWithLimit([], 5)).toEqual([]);\n  const { tasks, controls, started } = controlledTasks(3);\n  const pool = runWithLimit(tasks, 10);\n  await tick();\n  expect(started).toEqual([0, 1, 2]);\n  controls.forEach((d, i) => d.resolve(i));\n  expect(await pool).toEqual([0, 1, 2]);\n});\n\ntest('plain values and synchronous task functions work', async () => {\n  expect(await runWithLimit([() => 1, () => Promise.resolve(2), async () => 3], 2)).toEqual([1, 2, 3]);\n});\n\ntest('the first error rejects the pool and stops new tasks', async () => {\n  const { tasks, controls, started } = controlledTasks(4);\n  const pool = runWithLimit(tasks, 2);\n  await tick();\n  const boom = new Error('boom');\n  controls[1].reject(boom);\n  let caught = null;\n  try {\n    await pool;\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(boom);\n  controls[0].resolve('late');\n  await tick();\n  expect(started).toEqual([0, 1]);\n});\n\ntest('a task function that throws synchronously rejects the pool', async () => {\n  const error = new TypeError('bad task');\n  let caught = null;\n  try {\n    await runWithLimit([() => 1, () => { throw error; }, () => 3], 1);\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(error);\n});\n\ntest('invalid limit gives RangeError', async () => {\n  for (const limit of [0, -1, 1.5, NaN]) {\n    let caught = null;\n    try {\n      await runWithLimit([() => 1], limit);\n    } catch (e) {\n      caught = e;\n    }\n    expect(caught).toBeInstanceOf(RangeError);\n  }\n});\n\ntest('performance: 20 000 tasks with limit 50', async () => {\n  let running = 0;\n  let maxRunning = 0;\n  const tasks = Array.from({ length: 20000 }, (_, i) => () => {\n    running++;\n    maxRunning = Math.max(maxRunning, running);\n    return Promise.resolve(i).then((v) => {\n      running--;\n      return v;\n    });\n  });\n  const results = await runWithLimit(tasks, 50);\n  expect(results).toHaveLength(20000);\n  expect(results[19999]).toBe(19999);\n  expect(results.reduce((a, b) => a + b, 0)).toBe((19999 * 20000) / 2);\n  expect(maxRunning).toBeLessThanOrEqual(50);\n});\n"}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.138Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Skrypt migracyjny musi wywołać zewnętrzne API dla 20 000 rekordów. "},{"type":"text","text":"Promise.all(records.map(call))","marks":[{"type":"code"}]},{"type":"text","text":" wystartuje wszystko naraz i API odpowie błędem 429 albo padnie. Potrzebna jest "},{"type":"text","text":"pula","marks":[{"type":"bold"}]},{"type":"text","text":" – najwyżej "},{"type":"text","text":"limit","marks":[{"type":"code"}]},{"type":"text","text":" zadań w locie, a następne startuje, gdy tylko zwolni się miejsce. Zadanie dotyczy JavaScriptu/TypeScriptu (Node.js, przeglądarka) – obietnic i pętli zdarzeń."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"runWithLimit(tasks, limit)","marks":[{"type":"code"}]},{"type":"text","text":" – "},{"type":"text","text":"tasks","marks":[{"type":"code"}]},{"type":"text","text":" to tablica "},{"type":"text","text":"funkcji","marks":[{"type":"bold"}]},{"type":"text","text":" (nie obietnic!), z których każda po wywołaniu zwraca obietnicę albo zwykłą wartość. Funkcja zwraca obietnicę, która:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"rozwiązuje się tablicą wyników w "},{"type":"text","text":"kolejności zadań","marks":[{"type":"bold"}]},{"type":"text","text":" (nie kolejności zakończenia),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"uruchamia zadania w kolejności tablicy i nigdy nie trzyma w locie więcej niż "},{"type":"text","text":"limit","marks":[{"type":"code"}]},{"type":"text","text":" naraz,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"startuje kolejne zadanie "},{"type":"text","text":"od razu","marks":[{"type":"bold"}]},{"type":"text","text":", gdy któreś się zakończy (bez czekania na całą „paczkę”),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"przy pierwszym błędzie (odrzucona obietnica albo wyjątek rzucony przez funkcję zadania) odrzuca się tym błędem i "},{"type":"text","text":"nie startuje","marks":[{"type":"bold"}]},{"type":"text","text":" już nowych zadań; trwające mogą dobiec do końca, ale ich wyniki są ignorowane,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"dla pustej tablicy rozwiązuje się "},{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"dla "},{"type":"text","text":"limit","marks":[{"type":"code"}]},{"type":"text","text":", który nie jest dodatnią liczbą całkowitą, odrzuca się błędem "},{"type":"text","text":"RangeError","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"przyklad"},"content":[{"type":"text","text":"Przykład"}]},{"type":"paragraph","content":[{"type":"text","text":"limit = 2","marks":[{"type":"code"}]},{"type":"text","text":", zadania trwają: A – 300 ms, B – 100 ms, C – 100 ms, D – 50 ms:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Czas [ms]"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Zdarzenie"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"0"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"start A i B"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"100"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"koniec B → start C"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"200"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"koniec C → start D"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"250"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"koniec D"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"300"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"koniec A → wynik "},{"type":"text","text":"[A, B, C, D]","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"ograniczenia"},"content":[{"type":"text","text":"Ograniczenia"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Do 20 000 zadań, "},{"type":"text","text":"1 ≤ limit ≤ 1 000","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"oczekiwana-zlozonosc"},"content":[{"type":"text","text":"Oczekiwana złożoność"}]},{"type":"paragraph","content":[{"type":"text","text":"Narzut puli "},{"type":"text","text":"O(n)","marks":[{"type":"bold"}]},{"type":"text","text":" czasu i "},{"type":"text","text":"O(n)","marks":[{"type":"bold"}]},{"type":"text","text":" pamięci (na wyniki); bez sortowania i bez "},{"type":"text","text":"shift()","marks":[{"type":"code"}]},{"type":"text","text":" w pętli."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/promise-pool/","title":"LeetCode 2636 – Promise Pool","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:53.147Z","updatedAt":"2026-11-27T08:22:53.147Z"}