生成器函数

生成器函数

协程:跑在线程上面的一种轻量级的东西

一个线程每次只能运行一个协程。假设原先协程A在线程上运行着,那么只有协程A交出线程的控制权,才能让B协程运行

生成器函数中的挂起状态(即切换到外部函数),其实就是协程的切换

  • 举个栗子,思考一下它会输出什么?

    function * gen(){
        let one = yield 'hello'
        console.log(one);
        yield 'world'
    }
    let iterator = gen()  //注意,你在函数内可以拿到iterator这个变量,这是生成器函数独有的特征
    console.log(iterator.next());
    iterator.next('aaa')
    
  • 这个例子也值得深究和探讨

    setTimeout(function () {
        console.log(111);
        setTimeout(function () {
            console.log(222);
            setTimeout(function () {
                console.log(333);
            },3000)
        },2000)
    },1000)
    setTimeout(function () {
        console.log(444);
        setTimeout(function () {
            console.log(555);
            setTimeout(function () {
                console.log(666);
            },3000)
        },2000)
    },1000)
    
    //-----------
    	function a1() {
            setTimeout(function () {
                console.log(111);
            },1000)
        }
        function a2() {
            setTimeout(function () {
                console.log(222);
            },2000)
        }
        function a3() {
            setTimeout(function () {
                console.log(333);
            },3000)
        }
    
        a1()
        a2()
        a3()
    
    //--------------
    function a1() {
            setTimeout(function () {
                console.log(111);
                iterator.next()
            },1000)
        }
        function a2() {
            setTimeout(function () {
                console.log(222);
                iterator.next()
            },2000)
        }
        function a3() {
            setTimeout(function () {
                console.log(333);
            },3000)
        }
    
        function * gen(){
            yield a1()
            yield a2()
            yield a3()
        }
    
        let iterator=gen()
        iterator.next()
    
  • 你猜会输出多少个111?

    let asd=function (count) {
        console.log(`剩余${count}次抽奖机会`);
    }
    let remain=function * (count){
        while (count>0){
            count--
            yield asd(count)
        }
    }
    let star=remain(5)
    while (!star.next().done){
        console.log(111);
        star.next()
    }
    

参考链接:https://juejin.cn/post/7029324739055190046

posted @   朱在春  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示