實現簡單的generators自動執行Co 模塊

let axios = require("axios")
var co = require('co');
/**
 * 實現簡單的Co 模塊 自動執行next
 */
let step1 = () => {
  return axios.get('https://movie2.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=0', {
    params: {
      ID: 12345
    }
  })
}

let step2 = () => {
  return 'hello,world'
}

let step3 = () => {
  return () => {
    return 'My is Function'
  }
}
function MyCo(generator) {
  let generators = generator()
  return new Promise(function (resolve, reject) {
    function next(nextValue) {
      try {
        
        if (nextValue.done) {
          resolve()
          return;
        }
        if (!next.done) {
          //如果是函數直接返回內部函數供generator自行處理
          if (typeof nextValue.value === 'function') {
            //回覆yield 將執行指向下一個函數執行,並將nextValue.value當作結果返回
            next(generators.next(nextValue.value))
          }
          //如果是字符串直接將字符串返回
          if (typeof nextValue.value == 'string') {
            next(generators.next(nextValue.value))
          }
          //判斷是否是Promise異步使用
          if (Object.prototype.toString.call(nextValue.value) == '[object Promise]') {
            nextValue.value.then((res) => {
              next(generators.next(res.data))
            }).catch((error) => {
              //異常處理
              reject(error)
            })
          }
        }
      } catch (err) {
        console.log(err)
      }
    }
    next(generators.next())

  })

}
function* f() {
  let FnString = yield step3()
  console.log(FnString()) //My is Function
  let res = yield step1();
  console.log(res)
  let string = yield step2()
  console.log(string) //hello,world

}

MyCo(f).then(() => {
  console.log('執行結束')
}).catch((error) => {
  console.log('異常捕獲')
  console.log(error)
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章