Eric Bower
·
26 Aug 24
fx.md
1---
2title: fx
3description: Utilities to handle complex async flow control
4---
5
6`fx` (pronounced Effects) are helper functions to make async flow control
7easier.
8
9# parallel
10
11The goal of `parallel` is to make it easier to cooridnate multiple async
12operations in parallel, with different ways to receive completed tasks.
13
14All tasks are called with `fx.safe` which means they will never throw an
15exception. Instead all tasks will return a Result object that the end
16development must evaluate in order to grab the value.
17
18```ts
19import { parallel } from "starfx";
20
21function* run() {
22 const task = yield* parallel([job1, job2]);
23 // wait for all tasks to complete before moving to next yield point
24 const results = yield* task;
25 // job1 = results[0];
26 // job2 = results[1];
27}
28```
29
30Instead of waiting for all tasks to complete, we can instead loop over tasks as
31they arrive:
32
33```ts
34function* run() {
35 const task = yield* parallel([job1, job2]);
36 for (const job of yield* each(task.immediate)) {
37 // job2 completes first then it will be first in list
38 console.log(job);
39 yield* each.next();
40 }
41}
42```
43
44Or we can instead loop over tasks in order of the array provided to parallel:
45
46```ts
47function* run() {
48 const task = yield* parallel([job1, job2]);
49 for (const job of yield* each(task.sequence)) {
50 // job1 then job2 will be returned regardless of when the jobs
51 // complete
52 console.log(job);
53 yield* each.next();
54 }
55}
56```