ES6-Generator使用與改寫
阿新 • • 發佈:2019-05-06
註意 value 多次 func next ada 解決 tor err
用Generator封裝Symbol中的iterator方法:
註意:Generator的function後必須寫*
config:分別有3個txt文件,兩個文件寫路徑,一個文件寫要輸出的內容
前置寫法,node引入fs:
let fs = require(‘fs‘); function read(path){ return new Promise((res, rej) => { fs.readFile(path, ‘utf-8‘, (err,data) => { if(data){ res(data); }else{ rej(err); } }) }) }
當前的叠代方法: let obj = { 0: ‘a‘, 1: ‘b‘, 2: ‘c‘, length:4, [Symbol.iterator]: function (){ let index = 0; let next = () => {return { value: this[index], done: this.length == ++index } } return { next } } } console.log([...obj]);//(3) ["a", "b", "c"]for(let p of obj){ console.log(p);//a b c } 改寫後的方法: let obj = { 0: ‘a‘, 1: ‘b‘, 2: ‘c‘, length:3, [Symbol.iterator]: function* (){ let index = 0; while(index != this.length){ yield this[index++] } } } console.log([...obj]);//(2) ["a", "b"] for(let p of obj){ console.log(p);//a b }
用promise解決回調地獄問題與Generator方法對比
let fs = require(‘fs‘); function read(path){ return new Promise((res, rej) => { fs.readFile(path, ‘utf-8‘, (err,data) => { if(data){ res(data); }else{ rej(err); } }) }) } read(‘./number.txt‘).then((value) => { return read(value); }).then((value) => { return read(value); }).then((value) => { console.log(value); }) 以上缺點調用太多次then方法
那麽我們用Generator方法解決一下回調地獄
function * readA() { let val1 = yield read(‘./number.txt‘); let val2 = yield read(val1); let val3 = yield read(val2); return val3; } //返回Generator對象 let oG = readA(); let {value, done} = oG.next(); value.then((val) => { let {value, done} = oG.next(val); value.then((val) => { let {value, done} = oG.next(val); value.then((val) => { console.log(val) }) }) })
缺點:與回調地獄無區別
Generator優化:
註意:必須引入fs模塊才能運行
function * readA() { let val1 = yield read(‘./number.txt‘); let val2 = yield read(val1); let val3 = yield read(val2); return val3; } function Co(oIt){ return new Promise((res, rej) => { let next = (data) => { let {value, done} = oIt.next(data); if(done != true){ value.then((val) => { next(val); }) }else{ res(value); } } next(); }) } Co(readA()).then((val) => { console.log(val) })
node有co模塊,在npm下載使用,效果一樣
ES6-Generator使用與改寫