ES6新的数据类型 generato,在AJAX中的应用

1、next()方法会执行generator的代码,然后,每次遇到yield x;就返回一个对象{value: x, done: true/false},然后“暂停”。返回的value就是yield的返回值,done表示这个generator是否已经执行结束了。如果donetrue,则value就是return的返回值。

当执行到donetrue时,这个generator对象就已经全部执行完毕,不要再继续调用next()了。

mounted(){
        var _this = this;
        function ajax(url) {
            // 当请求执行完了之后,执行到then之后,又执行到了next();进行下一步请求
            _this.$ajax.get(url).then(res=>{
                consrdata.next(res);
            })
        }
        function* step() {
            const users = yield ajax('http://220.241.21.69:8088');
            console.log(users)
            const fisterUser = yield ajax('http://220.241.21.69:8088');
            console.log(fisterUser)
            const flolowers = yield ajax('http://220.241.21.69:8088')
            console.log(flolowers)
        }
        var consrdata=step();
        consrdata.next();//开始执行第一步

},

 

2、第二个方法是直接用for ... of循环迭代generator对象,这种方式不需要我们自己判断done

mounted(){
        var _this = this;
        function ajax(url) {
            // 当请求执行完了之后,执行到then之后,又执行到了next();进行下一步请求
            _this.$ajax.get(url).then(res=>{
                console.log(res)
            })
        }
        function* step() {
            const users = yield ajax('http://220.241.21.69:8088');
            const fisterUser = yield ajax('http://220.241.21.69:8088');
            const flolowers = yield ajax('http://220.241.21.69:8088')
        }

        for(var i of step()){
            
        }

},

 

posted @ 2020-02-28 15:34  秃头的铲屎官  Views(314)  Comments(0Edit  收藏  举报