File tree Expand file tree Collapse file tree 3 files changed +56
-1
lines changed Expand file tree Collapse file tree 3 files changed +56
-1
lines changed Original file line number Diff line number Diff line change 19
19
},
20
20
"homepage" : " https://github.com/palashmon/learn-generators#readme" ,
21
21
"dependencies" : {
22
- "moment" : " ^2.24.0"
22
+ "co" : " ^4.6.0" ,
23
+ "moment" : " ^2.24.0" ,
24
+ "node-fetch" : " ^2.6.0"
23
25
}
24
26
}
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Going Async With ES6 Generators
3
+ * With one tiny utility function we’ll unlock the full power of generators
4
+ * to make them work well with Promises and thus be the perfect tool
5
+ * for asynchronous flows in our apps.
6
+ */
7
+ const fetch = require ( 'node-fetch' ) ;
8
+ const { log } = require ( '../log' ) ;
9
+
10
+ const url = 'http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json' ;
11
+
12
+ // Generator function
13
+ function * createQuoteFetcher ( ) {
14
+ const response = yield fetch ( url ) ;
15
+ const quote = yield response . json ( ) ;
16
+ return `${ quote . quoteText } — ${ quote . quoteAuthor } ` ;
17
+ }
18
+
19
+ // Co-routine utility function to return yield value
20
+ const coroutine = gen => {
21
+ const generator = gen ( ) ;
22
+
23
+ const handle = result => {
24
+ if ( result . done ) return Promise . resolve ( result . value ) ;
25
+ return Promise . resolve ( result . value ) . then ( res => handle ( generator . next ( res ) ) ) ;
26
+ } ;
27
+
28
+ return handle ( generator . next ( ) ) ;
29
+ } ;
30
+
31
+ // Call the Co-routine function
32
+ const quoteFetcher = coroutine ( createQuoteFetcher ) ;
33
+ quoteFetcher . then ( quote => log ( quote ) ) . catch ( err => log ( 'ERROR: ' , err ) ) ;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Going Async With ES6 Generators
3
+ * With one tiny npm utility package
4
+ */
5
+ const fetch = require ( 'node-fetch' ) ;
6
+ const co = require ( 'co' ) ;
7
+ const { log } = require ( '../log' ) ;
8
+
9
+ const url = 'http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json' ;
10
+
11
+ // Generator function
12
+ function * createQuoteFetcher ( ) {
13
+ const response = yield fetch ( url ) ;
14
+ const quote = yield response . json ( ) ;
15
+ return `${ quote . quoteText } — ${ quote . quoteAuthor } ` ;
16
+ }
17
+
18
+ // Call the Co-routine function
19
+ const quoteFetcher = co ( createQuoteFetcher ) ;
20
+ quoteFetcher . then ( quote => log ( quote ) ) . catch ( err => log ( 'ERROR: ' , err ) ) ;
You can’t perform that action at this time.
0 commit comments