Exercise 5: Sequential Runner

Problem Statement

Create a function `series(tasks)` that runs tasks one-by-one (promise returning).

Sample Output:

await series([() => Promise.resolve(1), () => Promise.resolve(2)]) => [1, 2]
await series([() => fetchUser(), () => fetchPosts()]) => [userData, postsData] (sequential)

Solution

const series = async (tasks) => {
  const out = [];
  for (const t of tasks) out.push(await t());
  return out;
};

Explanation

Overall Goal:

  • Multiple async tasks ko sequential me run karna (one-by-one).
  • Pehla complete → phir dusra start.

Solution:

  • const series = async (tasks) => { const out = []; for (const t of tasks) out.push(await t()); return out; };

Line 1: Async function

  • const series = async (tasks) => {
  • tasks → array of functions (har function Promise return karta hai).

Line 2: Output array

  • const out = []; → results store karne ke liye.

Line 3: Sequential loop

  • for (const t of tasks) out.push(await t());
  • for...of → tasks array ko traverse.
  • await t() → current task execute → complete hone tak wait.
  • out.push(...) → result ko array me add.
  • Important: await sequential execution guarantee karta hai.

Line 4: Return results

  • return out; → sabhi results ka array return.

Example:

  • series([() => fetchUser(), () => fetchPosts()])
  • Step 1: fetchUser() → complete → result store.
  • Step 2: fetchPosts() → start → complete → result store.
  • Return: [userData, postsData].

Real world:

  • Dependent APIs: pehla API ka result dusre me use hota hai.
  • Data pipelines: step-by-step processing.
  • Sequential operations: order important hai.