关于javascript:ES6中的Generator函数

6次阅读

共计 1877 个字符,预计需要花费 5 分钟才能阅读完成。

明天小编发现一个 es6 中的新概念,同时也接触到了一个新关键字 yeild,上面我就简略和大家聊聊 es6 中的 generator 函数。大家还能够关注我的微信公众号,蜗牛全栈。
一、函数申明:在 function 和函数名之间存在星号,并应用关键字 yeild

function* foo(){for(let i = 0;i<3;i++){console.log(i) // 什么也没输入
        yield i
    }
}

console.log(foo()) // Generator

二、next 办法

function* foo(){for(let i = 0;i<3;i++){yield i}
}

let f = foo()
// f.next() 返回 yeild 前面的表达式
console.log(f.next()) // {value:0,done:false}
console.log(f.next()) // {value:1,done:false}
console.log(f.next()) // {value:2,done:false}
console.log(f.next()) // {value:undefind,done:true}

三、yeild 只能在 generator 函数外部应用,不能在里面应用

function* gen(agrs){
    agrs.forEach(item => {yield item += 1})
}
gen() // 报错:

四、next 函数返回值

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

五、实例敲 7 游戏:以后源码只是将 7 的倍数打印进去

function* count(x=1){while(true){if(x%7 === 0){yield x}
        x++
    }
}
// 能够一步一步执行,避免了死循环的问题
let n = count()
console.log(n.next().value) // 7
console.log(n.next().value) // 14
console.log(n.next().value) // 21
console.log(n.next().value) // 28
console.log(n.next().value) // 35

六、对异步的治理:(目录构造:在以后文件下存在一个 static 文件夹,文件夹内有三个文件 a.json、b.json、c.json。每个文件内是一个对象,别离为 {a:” 我是 a ”}、{b:” 我是 b ”}、{c:” 我是 c ”})

function ajax(url, callback) {
    // 1、创立 XMLHttpRequest 对象
    var xmlhttp
    if (window.XMLHttpRequest) {xmlhttp = new XMLHttpRequest()
    } else { // 兼容晚期浏览器
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
    }
    // 2、发送申请
    xmlhttp.open('GET', url, true)
    xmlhttp.send()
    // 3、服务端响应
    xmlhttp.onreadystatechange = function () {if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {var obj = JSON.parse(xmlhttp.responseText)
            // console.log(obj)
            callback(obj)
        }
    }
}

function request(url){
    ajax(url,res=>{getData.next(res)
    })
}
function* gen(){let res1 = yeild request("static/a.json")
    console.log(res1) // {a:"我是 a"}
    let res2 = yeild request("static/b.json")
    console.log(res2) // {b:"我是 b"}
    let res3 = yeild request("static/c.json")
    console.log(res3) // {c:"我是 c"}
}

let getData = gen()
getData.next()
正文完
 0