TypeScript: Tasks running at the same time

Start several timed tasks together and see the order they finish in, then collect their results in the original order.

What to build

A program that runs tasks in parallel with timers and promises.

Requirements

  • Declare interface Task { name: string; ms: number } and async function run(task: Task): Promise<string> that waits ms milliseconds with setTimeout, prints done NAME, and returns the name.
  • Start every task at once and wait for them with Promise.all; then print all done: NAME, NAME, ... in the input order.

Input

Line 1: n. Then n lines NAME MS.

Output

n done lines, in the order the tasks finish, then the summary.

Constraints

1 ≤ n ≤ 20; 0 ≤ MS ≤ 10000; tasks with the same time finish in input order.

Example

Input:

3
download 300
resize 100
upload 200

Output:

done resize
done upload
done download
all done: download, resize, upload

Why it works

All the timers start together, so each task finishes after its own time rather than after the sum of the times, and Promise.all hands back the results in the order they were asked for, not the order they arrived.

Examples

Example 1 · Input
3
download 300
resize 100
upload 200
Expected output
done resize
done upload
done download
all done: download, resize, upload
Example 2 · Input
2
a 50
b 50
Expected output
done a
done b
all done: a, b

Hints

Hint 1

An async function run(task: Task): Promise<string> can await a timer and then print.

Hint 2

Promise.all keeps the order of its input, whatever order the tasks finish in.

Solution

Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";

interface Task {
  name: string;
  ms: number;
}

function wait(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function run(task: Task): Promise<string> {
  await wait(task.ms);
  console.log("done " + task.name);
  return task.name;
}

async function main(): Promise<void> {
  const n = Number(read());
  const tasks: Task[] = [];
  for (let i = 0; i < n; i++) {
    const [name, ms] = read().split(" ");
    tasks.push({ name, ms: Number(ms) });
  }
  const names: string[] = await Promise.all(tasks.map(run));
  console.log("all done: " + names.join(", "));
}

main();

Lesson: Async code with types →