Skip to content

Commit 8607ffc

Browse files
committed
Generators and async - Sample
1 parent cc24127 commit 8607ffc

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

‎README.md

+32
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,38 @@ The fact that generators-as-observers pause while they wait for input makes them
257257
* **Intermediate chain members:** Generators that have a parameter target. They receive data via yield and send data via target.next().
258258
* **Last chain member:** A generator that has no parameter target and only receives data.
259259
260+
261+
### Generators and Async
262+
Here's an example to explain the concepts via setTimeouts as a replacement for an async operation.
263+
264+
```javascript
265+
function getFirstName() {
266+
setTimeout(function() {
267+
gen.next('Jerry');
268+
}, 2000);
269+
// returns undefined
270+
// But next() is not called until the async activity is finished
271+
// After which var a is set to 'Jerry'
272+
}
273+
274+
function getSecondName() {
275+
setTimeout(function() {
276+
gen.next('Seinfeld');
277+
}, 3000);
278+
// Same as getFirstName(), fn is paused until next() is called
279+
// And then the value is assigned to var b
280+
}
281+
282+
function* getFullName() {
283+
var firstName = yield getFirstName();
284+
var lastName = yield getSecondName();
285+
console.log(firstName + ' ' + lastName); // Jerry Seinfeld
286+
}
287+
288+
var gen = getFullName();
289+
gen.next(); // Initialize generator flow to first `yield`
290+
```
291+
260292
> [More Code](3-generators.js)
261293
262294
### Links

0 commit comments

Comments
 (0)