generator函数学习

function fetchDate(name) {
    // 模拟异步请求
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(name)
      },1000)
    })
  }
  function *dataLoader() {
    const d1 = yield fetchDate('d1');
    console.info('d1', d1)
    const d2 = yield fetchDate('d2');
    console.info('d2', d2)
  }

  // 最原始的一步一步迭代执行
  function run1(generator) {
    const gen = generator();
    gen.next().value.then((rps) => {
      console.info('--rps', rps)
      gen.next(rps).value.then((rps2 => {
        console.info('--rps2', rps2)
        gen.next(rps2)
      }))
    })
  }
  // run1(dataLoader)
  // 稍微封装一下 递归迭代
  function run2(generator) {
    const gen = generator();
    function nextStep(data) {
      const {value, done} = gen.next(data);
      if (!done) {
        value.then((rps) => {
          nextStep(rps)
        })
      }
    }
    nextStep()
  }
  // run2(dataLoader)
  // 兼容处理value不是一个promise的请求
  function *dataLoader2() {
    const d1 = yield fetchDate('d1');
    console.info('d1', d1)
    const d2 = yield fetchDate('d2');
    console.info('d2', d2)
    const d3 = yield 'hello world';
    console.info('d3', d3)
  }
  function run3(generator) {
    const gen = generator();
    function nextStep(data) {
      const {value, done} = gen.next(data);
      if (!done) {
        if (typeof value === 'function') {
          value.then((rps) => {
            nextStep(rps)
          }, reason => {
            generator.throw(reason)
          })
        } else {
          nextStep(value)
        }
      }
    }
    nextStep()
  }
  // run3(dataLoader2)
  // 增加一个语法糖
  function *dataLoader3() {
    const d1 = yield fetchDate('d1');
    console.info('d1', d1)
    const d2 = yield fetchDate('d2');
    console.info('d2', d2)
    const d3 = yield 'hello world';
    console.info('d3', d3)
    const {limit} = yield '';
    console.info('d4', limit.color)
  }
  function run4(generator) {
    const gen = generator();
    function nextStep(data) {
      const {value, done} = gen.next(data);
      if (!done) {
        if (typeof value === 'function') {
          value.then((rps) => {
            nextStep(rps)
          }, reason => {
            generator.throw(reason)
          })
        } else if(value === '') {
          const currentPageStore = {
            limit: {
              name: '123',
              size: 'XXL',
              color: 'blue'
            }
          }
          nextStep(currentPageStore)
        } else {
          nextStep(value)
        }
      }
    }
    nextStep()
  }
  run4(dataLoader3)

 

posted @ 2017-12-27 11:34  韭菜茄子  阅读(641)  评论(0)    收藏  举报