企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
es6提供的异步编程解决方案 值js中可看成一个特殊的函数,由function+*+函数名(){}构成 ``` function*gen(){ console.log("hello world") } let iterator=gen(); iterator.next();//调用next才输出hello world! ``` 由yield分割代码,每调用一个next执行一个yield语句块 ``` function*gen(){ console.log("a") yield "1"; console.log("b") yield "2"; console.log("c") yield "3"; console.log("d") yield "4"; } let iterator=gen(); iterator.next();//a iterator.next();//b iterator.next();//c iterator.next();//d iterator.next();//无输出 function*gen(){ yield "1"; yield "2"; yield "3"; yield "4"; } for (let v of gen()) { console.log(v);//一次输出1,2,3,4 } ``` 生成器参数 ``` function*gen(arg){ console.log(arg);//AAA } let iterator1=gen("AAA"); iterator1.next(); function*gen(){ let one=yield 111; console.log(one) let two=yield 222; console.log(two); let three=yield 333; console.log(three) } let iterator2=gen(); iterator2.next(); iterator2.next("BBB");//由one接收 iterator2.next("CCC");//由two接收 iterator2.next("DDD");//由three接收 ``` 实例: ``` //1s后控制台输出11,2s后输出22,3s后输出33 //更多输出就嵌套更多,回调地狱 setTimeout(()=>{ console.log(11) setTimeout(()=>{ console.log(22) setTimeout(()=>{ console.log(33) },3000) },2000) },1000) //生成器实现解决回调地狱 function one(){ setTimeout(()=>{ console.log(11); iterator.next(); },1000) } function two(){ setTimeout(()=>{ console.log(22); iterator.next(); },2000) } function three(){ setTimeout(()=>{ console.log(33); iterator.next(); },3000) } function * gen(){ yield one(); yield two(); yield three(); } let iterator=gen(); iterator.next(); ``` ``` function getUsers(){ setTimeout(()=>{ let users="用户数据"; iterator.next(users); },1000) } function getOrders(){ setTimeout(()=>{ let orders="用户订单"; iterator.next(orders); },1000) } function getGoods(){ setTimeout(()=>{ let goods="用户商品"; iterator.next(goods); },1000) } function * gen(){ let users = yield getUsers(); console.log(users); let orders = yield getOrders(); console.log(orders); let goods = yield getGoods(); console.log(goods); } let iterator=gen(); iterator.next(); ```