repos / starfx

supercharged async flow control library.
git clone https://github.com/neurosnap/starfx.git

commit
d760ff8
parent
2b5e614
author
Eric Bower
date
2023-09-02 14:49:50 +0000 UTC
doc: readme
1 files changed,  +17, -9
M README.md
+17, -9
 1@@ -30,23 +30,31 @@ article
 2 [The gotcha of unhandled promise rejections](https://jakearchibald.com/2023/unhandled-rejections/):
 3 
 4 ```ts
 5-import { json, main, parallel, request } from "starfx";
 6+import { json, main, parallel, request, each } from "starfx";
 7 
 8-function* fetchMovie(title: string) {
 9-  const response = yield* request(`/movies/${title}`);
10+function* fetchChapter(title: string) {
11+  const response = yield* request(`/chapters/${title}`);
12   const data = yield* json(response);
13   return data;
14 }
15 
16 const task = main(function* () {
17-  const movies = ["titanic", "avatar", "good will hunting"];
18-  const ops = movies.map((title) => () => fetchMovie(title));
19+  const chapters = ["01", "02", "03"];
20+  const ops = chapters.map((title) => () => fetchChapter(title));
21 
22   // parallel returns a list of `Result` type
23-  const group = yield* parallel(ops);
24-  // wait for results
25-  const results = yield* group;
26-  return results;
27+  const chapters = yield* parallel(ops);
28+
29+  // make http requests in parallel but process them in sequence (e.g. 01, 02,
30+  03)
31+  for (const result of yield* each(chapters.sequence)) {
32+    if (result.ok) {
33+      console.log(result.value);
34+    } else {
35+      console.error(result.error);
36+    }
37+    yield* each.next;
38+  }
39 });
40 
41 const results = await task;