Skip to content

Commit 589e5ec

Browse files
committed
Going Async With ES6 Generators
1 parent 9787740 commit 589e5ec

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
},
2020
"homepage": "https://github.com/palashmon/learn-generators#readme",
2121
"dependencies": {
22-
"moment": "^2.24.0"
22+
"co": "^4.6.0",
23+
"moment": "^2.24.0",
24+
"node-fetch": "^2.6.0"
2325
}
2426
}

src/3-Going-Async/ex1.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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));

src/3-Going-Async/ex2.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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));

0 commit comments

Comments
 (0)