今天小編髮現一個es6中的新概念,同時也接觸到了一個新關鍵字yeild,下面我就簡單和大家聊聊es6中的generator函式。大家還可以關注我的微信公眾號,蝸牛全棧。

一、函式宣告:在function和函式名之間存在星號,並使用關鍵字yeild

  1. function* foo(){
  2. for(let i = 0;i<3;i++){
  3. console.log(i) // 什麼也沒輸出
  4. yield i
  5. }
  6. }
  7.  
  8. console.log(foo()) // Generator

二、next方法

  1. function* foo(){
  2. for(let i = 0;i<3;i++){
  3. yield i
  4. }
  5. }
  6.  
  7. let f = foo()
  8. // f.next() 返回yeild後面的表示式
  9. console.log(f.next()) // {value:0,done:false}
  10. console.log(f.next()) // {value:1,done:false}
  11. console.log(f.next()) // {value:2,done:false}
  12. console.log(f.next()) // {value:undefind,done:true}

三、yeild只能在generator函式內部使用,不能在外面使用

  1. function* gen(agrs){
  2. agrs.forEach(item => {
  3. yield item += 1
  4. })
  5. }
  6. gen() // 報錯:

四、next函式返回值

  1. // next 返回yeild後面表示式返回的值
  2. function* gen(x){
  3. let y = 2 * (yield(x + 1))
  4. let z = yield(y/3)
  5. return x + y + z
  6. }
  7. let g = gen(5)
  8. console.log(g.next()) // {value:6,done:false}
  9. console.log(g.next()) // {value:NaN,done:false}
  10. console.log(g.next()) // {value:NaN,done:true}

五、例項敲7遊戲:當前原始碼只是將7的倍數打印出來

  1. function* count(x=1){
  2. while(true){
  3. if(x%7 === 0){
  4. yield x
  5. }
  6. x++
  7. }
  8. }
  9. // 可以一步一步執行,防止了死迴圈的問題
  10. let n = count()
  11. console.log(n.next().value) // 7
  12. console.log(n.next().value) // 14
  13. console.log(n.next().value) // 21
  14. console.log(n.next().value) // 28
  15. console.log(n.next().value) // 35

六、對非同步的管理:(目錄結構:在當前檔案下存在一個static資料夾,資料夾內有三個檔案a.json、b.json、c.json。每個檔案內是一個物件,分別為{a:"我是a"}、{b:"我是b"}、{c:"我是c"})

  1. function ajax(url, callback) {
  2. // 1、建立XMLHttpRequest物件
  3. var xmlhttp
  4. if (window.XMLHttpRequest) {
  5. xmlhttp = new XMLHttpRequest()
  6. } else { // 相容早期瀏覽器
  7. xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
  8. }
  9. // 2、傳送請求
  10. xmlhttp.open('GET', url, true)
  11. xmlhttp.send()
  12. // 3、服務端響應
  13. xmlhttp.onreadystatechange = function () {
  14. if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
  15. var obj = JSON.parse(xmlhttp.responseText)
  16. // console.log(obj)
  17. callback(obj)
  18. }
  19. }
  20. }
  21.  
  22. function request(url){
  23. ajax(url,res=>{
  24. getData.next(res)
  25. })
  26. }
  27. function* gen(){
  28. let res1 = yeild request("static/a.json")
  29. console.log(res1) // {a:"我是a"}
  30. let res2 = yeild request("static/b.json")
  31. console.log(res2) // {b:"我是b"}
  32. let res3 = yeild request("static/c.json")
  33. console.log(res3) // {c:"我是c"}
  34. }
  35.  
  36. let getData = gen()
  37. getData.next()