1
1
const API_URL = 'http://localhost:3000'
2
- async function * startConsumingAPI ( signal ) {
2
+
3
+ async function consumeAPI ( signal ) {
3
4
const response = await fetch ( API_URL , {
4
5
signal
5
6
} )
6
7
7
8
const reader = response . body
8
9
. pipeThrough ( new TextDecoderStream ( ) )
9
10
. pipeThrough ( parseNDJSON ( ) )
10
- . getReader ( )
11
11
12
- let done = false
13
- do {
14
- const res = await reader . read ( )
15
- done = res . done
16
- if ( done ) break
17
- yield res . value
18
- }
19
- while ( ! done )
12
+ return reader
20
13
}
21
14
22
15
function parseNDJSON ( ) {
@@ -38,37 +31,41 @@ function parseNDJSON() {
38
31
} )
39
32
}
40
33
41
- function appendToHTML ( { title, description, url_anime, image } , el ) {
42
- const card = `
43
- <article>
44
- <div class="text">
45
- <h3>${ title } </h3>
46
- <p>${ description . slice ( 0 , 100 ) } </p>
47
- <a href="${ url_anime } ">Here's why</a>
48
- </div>
49
- </article>
50
- `
51
- el . innerHTML += card
34
+ function appendToHTML ( el ) {
35
+ return new WritableStream ( {
36
+ async write ( { title, description, url_anime } ) {
37
+ const card = `
38
+ <article>
39
+ <div class="text">
40
+ <h3>[${ ++ counter } ] ${ title } </h3>
41
+ <p>${ description . slice ( 0 , 100 ) } </p>
42
+ <a href="${ url_anime } ">Here's why</a>
43
+ </div>
44
+ </article>
45
+ `
46
+ el . innerHTML += card
47
+ } ,
48
+ abort ( reason ) {
49
+ console . log ( 'aborted**' , reason )
50
+ }
51
+ } )
52
52
}
53
53
54
- const [ start , stop , cards ] = [ 'Start' , 'Stop' , 'cards' ] . map ( id => document . getElementById ( id ) )
54
+ const [
55
+ start ,
56
+ stop ,
57
+ cards
58
+ ] = [ 'Start' , 'Stop' , 'cards' ]
59
+ . map (
60
+ id => document . getElementById ( id )
61
+ )
55
62
56
63
let abortController = new AbortController ( )
64
+ let counter = 0
65
+
57
66
start . addEventListener ( 'click' , async ( ) => {
58
- const it = startConsumingAPI ( abortController . signal )
59
- let counter = 0
60
- try {
61
- for await ( const item of it ) {
62
- counter ++
63
- console . log ( 'item' , counter , item . title )
64
- appendToHTML ( item , cards )
65
- // if (counter >= 10) {
66
- // abortController.abort()
67
- // }
68
- }
69
- } catch ( error ) {
70
- if ( ! error . message . includes ( 'aborted' ) ) throw error
71
- }
67
+ const reader = await consumeAPI ( abortController . signal )
68
+ reader . pipeTo ( appendToHTML ( cards ) )
72
69
} )
73
70
74
71
stop . addEventListener ( 'click' , ( ) => {
0 commit comments