File tree 1 file changed +32
-0
lines changed
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -257,6 +257,38 @@ The fact that generators-as-observers pause while they wait for input makes them
257
257
* **Intermediate chain members:** Generators that have a parameter target. They receive data via yield and send data via target.next().
258
258
* **Last chain member:** A generator that has no parameter target and only receives data.
259
259
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
+
260
292
> [More Code](3-generators.js)
261
293
262
294
### Links
You can’t perform that action at this time.
0 commit comments