我是靠谱客的博主 炙热龙猫,这篇文章主要介绍generator函数及async的简单实现,现在分享给大家,希望可以做个参考。

generator函数概念

Generator函数是ES6提供的一种异步编程解决方案,从语法上,Generator函数一个状态机,封装了多个内部状态。
Generator函数被调用之后,返回遍历器对象,每次调用.next()方法,会执行到下一个yield语句之前。

function* gen(x){
            var res1 = yield x + 1;
            var res2 = yield x + 2;
            var res3 = yield x + 3;
 }
 var g = gen(3);
 console.log(g.next())//{value:4,done:false}
 console.log(g.next())//{value:5,done:false}
 console.log(g.next())//{value:6,done:false}

next方法内部传参

传入的参数将作为上个阶段异步任务的返回结果,如下面代码,第一个next中传入的参数并没有被输出。

function* gen(x){
      var res1 = yield x + 1;
      console.log(res1)//param2
      var res2 = yield x + 2;
       console.log(res2)//param3
       var res3 = yield x + 3;
       console.log(res3)//param4
}
var g = gen(3);
console.log(g.next('param1'))//{value: 4, done: false}
console.log(g.next('param2'))//{value: 5, done: false}
console.log(g.next('param3'))//{value: 6, done: false}
console.log(g.next('param4'))//{value: undefined, done: false}

用generator函数实现一个基本的async、await功能

function fetchData1() {
            return new Promise(resolve=>{
                setTimeout(()=>{
                    resolve('promise1的结果')
                },2000)
            })
        }
        function fetchData2() {
            return new Promise(resolve=>{
                setTimeout(()=>{
                    resolve('promise2的结果')
                },2000)
            })
        }

        function run(taskDef) {
            // 创建一个无使用限制的迭代器
            let task = taskDef();
            //开始执行任务
            let result = task.next();
            // 循环调用next()函数
            function step() {
                //如果任务未完成 , 则继续执行
                if(!result.done) {
                    if(result.value instanceof Promise) {
                        result.value.then(res=>{
                            result = task.next(res);
                            step();
                        })
                    } else {
                        result = task.next(result.value);
                        step();
                    }
                }
            }
            //开始执行迭代
            step();
        }

        //调用
        run(function *(){
            let contents = yield fetchData1();
            let test = yield fetchData2()
            console.log(contents,test);
            console.log('------')
        })

最后

以上就是炙热龙猫最近收集整理的关于generator函数及async的简单实现的全部内容,更多相关generator函数及async内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部