ES6 Generator 在抽獎和長輪詢場景中的應用

{
  // 抽獎次數限制
  let draw = function(count) {
    // 抽獎邏輯
    console.info(`剩餘抽獎次數${count}`)
  }
  let residue = function* (count) {
    while (count > 0) {
      count--
      yield draw(count)
    }
  }
  let star = residue(5)
  let btn = document.createElement('button')
  btn.id = 'start'
  btn.textContent = '抽獎'
  document.body.appendChild(btn)
  document.getElementById('start').addEventListener('click', function() {
    star.next()
  }, false)
}

{
  // 長輪詢
  let ajax = function* () {
    yield new Promise(function (resolve, reject) {
      setTimeout(function() {
        resolve({code:1})
      }, 200)
    })
  }

  let pull = function() {
    let genertaor = ajax()
    let step = genertaor.next()
    step.value.then(function (data) {
      if (data.code != 0) {
        setTimeout(function() {
          console.log('wait')
          pull()
        }, 1000)
      } else {
        console.log(data)
      }
    })
  }
  pull()
}

 

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