Node.js generator, and asynchronous operation iterator

1. Simple iterator model

 1 function makeIterator(arr) {
 2   let nextIndex = 0;
 3   return {
 4     next: () => {
 5       if (nextIndex < arr.length) {
 6         return { value: arr[nextIndex++], done: false };
 7       } else {
 8         return { done: true };
 9       }
10     }
11   };
12 }
13 
14 const it = makeIterator(["吃饭", "睡觉", "打豆豆"]);
15 
16 console.log("首先", it.next().value);
17 console.log("其次", it.next().value);
18 console.log("再次", it.next().value);
19 console.log("然后", it.next().value);
20 console.log("最后", it.next().value);

2. Generator Version:

. 1  function * makeIterator (ARR) {
 2    for (the let I = 0; I <arr.length; I ++ ) {
 . 3      the yield ARR [I];
 . 4    }
 . 5  }
 . 6 const makeIterator Gen = ([ "eat", "sleep" "Peas hit" ]);
 7 console.log ( "first" , gen.next ());
 8 console.log ( "Second" , gen.next ());
 9 console.log ( "again" , gen.next ());
 10 the console.log ( "and" , gen.next ());
 . 11 the console.log ( "last", gen.next ());

Builder print result:

. 1  [lambda] Node server2.js
 2 first value {: ' eat ' , DONE : to false }
 . 3 Second value {: ' sleep ' , DONE : to false }
 . 4 again value {: ' play Peas ' , DONE : to false }
 . 5 and { value: undefined, DONE : to true }
 . 6 last value {: undefined, DONE : to true }

Guess you like

Origin www.cnblogs.com/guoyinsheng/p/12081684.html