ES6生成器
//生成器就是一个特殊的函数 function* gen(params) { console.log("111"); yield '两只老虎'; console.log("222"); yield '跑得快'; console.log("333"); yield '真奇怪'; console.log("444"); } //执行获取迭代器对象,next方法会返回yieid后面的对象 let iterator = gen(); iterator.next(); iterator.next(); iterator.next(); iterator.next();
//生成器就是一个特殊的函数 function* gen(arg) { console.log(arg); let one = yield '两只老虎'; console.log(one); let two = yield '跑得快'; console.log(two); let three = yield '真奇怪'; console.log(three); } //执行获取迭代器对象,next方法会返回yieid后面的对象 let iterator = gen('AAA'); console.log(iterator.next()); //next方法可传入实参 console.log(iterator.next('BBB')); console.log(iterator.next("CCC")); console.log(iterator.next('DDD'));
//实例进行异步编程
首先 ,传统的js中存在异步调用回调地狱的现象,如果继续有异步任务,要不停的嵌套,如果需要读取很多数据 ,代码很那读懂
//异步编程回调地狱 由于js是单线程 如文件操作 网络操作 数据库操作 这些都要通过异步来完成 //定时器案例演示 //1s输出111,2s输出222.3s输出333 setTimeout(() => { console.log(111); setTimeout(() => { console.log(222); setTimeout(() => { console.log(333); }, 3000); }, 2000); }, 1000);
利用生成器函数来做
function one() { setTimeout(() => { console.log(111); iterator.next(); }, 1000); } function two() { setTimeout(() => { console.log(222); iterator.next(); }, 2000); } function three() { setTimeout(() => { console.log(333); iterator.next(); }, 3000); } function* gen() { yield one(); yield two(); yield three(); } //调用生成器函数 let iterator = gen(); //执行 iterator.next();