首页>>新闻中心>>ES6学习方法

Generator管理

来源: 本站    发布时间: 2021-03-01 23:11    阅读次数:

//Generator
    // function foo() {
    //     for (let i = 0; i<3; i++){
    //         console.log(i)
    //     }
    // }
    // foo()
    // function* foo() {
    //     for (let i = 0; i<3; i++){
    //         yield i
    //     }
    // }
    // let p = foo()
    // console.log(p.next())  //{value: 0, done: false}
    // console.log(p.next())  //{value: 1, done: false}
    // console.log(p.next())  //{value: 2, done: false}
    // console.log(p.next())  //{value: undefined, done: true}
    //Generator 不能作为构造函数使用,只能返回一个生成器对象 yield 只能在generator里面使用
   // function* gen(args) {
   //      args.forEach((item) => {
   //          yield item+1
   //      })
   // }  //这样使用就是错误的

    // 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()) //6
    // console.log(g.next()) //NaN
    // console.log(g.next()) //NaN
    // console.log(g.next()) //6
    // console.log(g.next(12)) //y=24 8
    // console.log(g.next(13)) //z=13 x=5 24+13+5=42

    // function* count(x=1) {
    //     while (true){
    //         if(x % 7 === 0){
    //             yield x
    //         }
    //         x++
    //     }
    // }
    // let n = count()
    // console.log(n.next().value)
    // console.log(n.next().value)
    // console.log(n.next().value)
    // console.log(n.next().value)
    let url1 = "http://192.168.0.105/es6/json/a.json"
    let url2 = "http://192.168.0.105/es6/json/b.json"
    let url3 = "http://192.168.0.105/es6/json/c.json"
    function ajax(url,callback) {
        var xmlhttp
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest()
        }else{
            xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
        }
        // 发送请求
        xmlhttp.open("GET", url, true)
        xmlhttp.send()
        //服务端的响应
        xmlhttp.onreadystatechange = function () {
            if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                var obj = JSON.parse(xmlhttp.response)
                //console.log(obj)
                callback(obj)
            }
        }
    }
    function request(url) {
        ajax(url, res=>{
            getData.next(res)
        })
    }
    function* gen() {
        let res1 = yield request(url1);
        console.log(res1)
        let res2 = yield request(url2);
        console.log(res2)
        let res3 = yield request(url3);
        console.log(res3)
    }
    let getData = gen()
    getData.next()
一起设计吧
上一篇: Promise 状态管理
BACK