迭代器函數的定義 迭代器中須要返回一個對象這個對象中須要有一個next方法,next方法調用後,能夠返回一個對象對象中有兩個參數 第一個done value迭代出的結果express
function * a() { let x = yield 100; console.log('x',x); let y = yield 200; console.log(y); let z = yield 300; return z } // let flag = false; // do { // let {done,value} = it.next(); // console.log(value); // flag = done; // } while (!flag);
let fs = require('mz/fs'); // let co = require('co'); // generator => async + await function * read() { // 能夠暫停 能夠支持promise let age = yield fs.readFile('./name.txt','utf8'); let adress = yield fs.readFile(age,'utf8'); let r = yield fs.readFile(adress,'utf8'); return r; } function co(it) { return new Promise((resolve,reject)=>{ // 異步線性執行怎麼實現 koa express function next(data) { let { value, done } = it.next(data); if(!done){ value.then(data=>{ next(data) }, reject); }else{ resolve(value); } } next(); }) } co(read()).then(data=>{ console.log(data); },err=>{ console.log(err); }); // let it = read(); // it.next().value.then(data=>{ // it.next(data).value.then(data=>{ // it.next(data).value.then(data=>{ // console.log(it.next(data).value); // }) // }) // })