ES6中的Generator函数

本文介绍了ES6中的Generator函数,包括其声明、next方法的使用,以及yeild关键字的功能。通过实例展示了Generator如何处理迭代、异步操作,如在7的游戏示例中避免死循环,以及在异步请求中的应用,如读取多个JSON文件。
摘要由CSDN通过智能技术生成

今天小编发现一个es6中的新概念,同时也接触到了一个新关键字yeild,下面我就简单和大家聊聊es6中的generator函数。大家还可以关注我的微信公众号,蜗牛全栈。在后续的React中间件会有相应的应用。

一、函数声明:在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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鹰3995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值