0
点赞
收藏
分享

微信扫一扫

异步解决方案1.generator函数 2.Promise,3.async await(1)

云卷云舒xj 2022-02-12 阅读 35

<!-- 异步编程 ajax 定时器 回调里面套回调,层层嵌套,回调地狱-->

 <!-- 解决方案:1.generator函数 2.Promise,3.async await -->

//定义一个Generator函数 function * 函数名(){}

        //在Generator函数内部,通过yield关键字使函数分步执行 按照顺序执行

        //yield相当于把代码拆分成代码块,每次执行一个代码块,然后程序挂起,等待上一个程序执行完再执行下一个

        function * helloWorld(){

            console.log("1");

            yield "hello";

            console.log("2");

            yield "world";

            console.log("3");

            return "end"

        }

        var gen = helloWorld()

        console.log(gen);

        //使用next方法,分段执行Generator函数

        console.log(gen.next());//next对应定义一个yield,暂停后续操作,yield后跟着的"hello"会作为value返回 done: false说明函数还没有执行完

        console.log(gen.next());//value:"world",done:false

        console.log(gen.next());//遇到return函数执行结束,value:"end",done:ture

       

        //Generator函数是一个分段执行的过程,yield用来把函数挂起(暂停),next()恢复执行 yield和next一一对应

举报

相关推荐

0 条评论