Iterator

已经部署Iterator接口的数据
array、map、set、string、TypeArray、NodeList、arguments

obj添加遍历起

  1. let obj={
  2. a:1,
  3. b:2,
  4. c:3,
  5. [Symbol.iterator](){
  6. let nextIndex=0;
  7. let map=new Map();
  8. for(let [key,value] of Object.entries(this)) {
  9. map.set(key,value)
  10. }
  11. let mapEnteries=[...map.entries()];
  12. return {
  13. next(){
  14. return nextIndex<mapEnteries.length?
  15. {value: mapEnteries[nextIndex++],done: false}:{
  16. value: undefined,done: true
  17. }
  18. }
  19. }
  20. }
  21. }
  22. for(let i of obj){
  23. console.log(i)
  24. }
  25. 使用generator函数
  26. let obj={
  27. a:0,
  28. b:9,
  29. [Symbol.iterator]: function *(){
  30. let nextIndex=0;
  31. let map=new Map();
  32. for(let [key,value] of Object.entries(this)) {
  33. map.set(key,value)
  34. }
  35. let mapEnteries=[...map.entries()];
  36. while(nextIndex<len){
  37. yield arr[nextIndex++]
  38. }
  39. }
  40. }

image.png

Generator

generator也是迭代器可以用for…of遍历

  1. function * foo(){
  2. let value1=yield 1;
  3. console.log(value1); //two
  4. let value2=yield 2;
  5. let value3=yield 3;
  6. }
  7. let iter=foo();
  8. iter.next('one')
  9. iter.next('two')
  1. let fs=require('fs');
  2. fs.readFile('./name.txt','utf-8',(err,data)=>{
  3. fs.readFile(data,'utf-8',(err,data)=>{
  4. fs.readFile(data,'utf-8',(err,data)=>{
  5. console.log(data)
  6. })
  7. })
  8. })
  9. function promisify(fn) {
  10. return function(...args) {
  11. return new Promise((resolve,reject)=>{
  12. fn(...args,(err,data)=>{
  13. if(err){
  14. reject(err);
  15. }else{
  16. resolve(data)
  17. }
  18. })
  19. })
  20. }
  21. }
  22. let readFile=promisify(fs.readFile);
  23. readFile('./name.txt','uft-8')
  24. .then(res=>readFile(res,'utf-8'))
  25. .then(res=>readFile(res,'utf-8'))
  26. .then(res=>console.log(res))
  27. function * read() {
  28. let value1=yield readFile('./name.txt','utf-8');
  29. let value2=yield readFile(value1,'utf-8');
  30. let value3=yield readFile(value2,'utf-8');
  31. console.log(value3)
  32. }
  33. let iter=read();
  34. let {value,done}=iter.next();
  35. value.then((val1)=>{
  36. let {value,done}=iter.next(val1);
  37. value.then((val2)=>{
  38. let {value,done}=iter.next(val2);
  39. value.then((val3)=>{
  40. console.log('val3',val3)
  41. })
  42. })
  43. })
  44. 优化:
  45. function Co(iter) {
  46. return new Promise((resolve,reject)=>{
  47. let next=(data)=>{
  48. let {value,done}=iter.next(data);
  49. if(done) {
  50. resolve(value);
  51. }else{
  52. value.then((val)=>{
  53. next(val)
  54. })
  55. }
  56. next();
  57. }
  58. })
  59. }
  60. let promise=Co(read());
  61. promise.then((val)=>{
  62. console.log(val);
  63. })