Node.jsの発電機、および非同期操作イテレータ

1.シンプルなイテレータモデル

1つの 関数makeIterator(ARR){
 2    LET nextIndex = 0 3    リターン{
 4      次:()=> {
 5        であれば(nextIndex < arr.length){
 6          戻り {値:ARR [nextIndex ++]、行わ:}。
7        } {
 8          リターン {行わ:}。
9        }
 10      }
 11    }。
12  }
 13  
14がmakeIteratorを=定数([ "吃饭"、 "睡觉"、 "打豆豆" ])。
15 
16はconsole.log( "首先" 、it.next()値。)。
17はconsole.log( "其次" 、it.next()値。)。
18はconsole.log( "再次" 、it.next()値。)。
19はconsole.log( "然后" 、it.next()値。)。
20はconsole.log( "最后"、it.next()値。)。

2.ジェネレーターバージョン:

1つの 関数 * {makeIterator(ARR)
 2    のための(; I <arr.length; I = 0せI ++ ){
 3      降伏ARR [I];
 4    }
 。5  }
 6。 makeIteratorジェンCONST =([ "食べる"、 "スリープ" "エンドウ豆は、ヒット" )];
 7はconsole.log( "第一" 、gen.next());
 8はconsole.log( "第二" 、gen.next());
 9はconsole.log( "再び" 、 gen.next());
 10はconsole.log( "及び" 、gen.next());
 図11はconsole.log( "最後"、gen.next())。

Builderの印刷結果:

。1  、λノードserver2.js
 2最初の値{:' 食べる'DONEfalseに}
 3。二値{:' スリープ'DONEfalseに}
 4。再び値{:' プレイエンドウ'DONEfalseに}
 。5及び{値:不定、DONEtrueに}
 6。最後の値{:不定、DONEtrueに }

おすすめ

転載: www.cnblogs.com/guoyinsheng/p/12081684.html