为什么使用ES6生成器
生活随笔
收集整理的這篇文章主要介紹了
为什么使用ES6生成器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
官方解釋:
1、異步編程,文件操作,網絡操作(ajax, request) 數據庫操作使用生成器操作更加方便;
2、有效的解決回調地獄的問題;
舉例:
請在控制臺 1s 后控制臺輸出 111 ,2s后輸出 222 ,3s后輸出 333。
(1)使用傳統的的回調寫法
setTimeout(() => {console.log(111);setTimeout(() => {console.log(222);setTimeout(() => {console.log(333);}, 3000);}, 2000);}, 1000);(2)使用生成器減少層級結構
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();第一次使用iterator.next()使程序走進one函數中,后續使用iterator.next()讓程序繼續讓下走;
對比發現,使用生成器的模式,再次添加邏輯功能,函數代碼不會再縮進了。也不用去關心原來的嵌套邏輯,代碼更加直觀易懂,方便操作;
(3)生成器函數參數
function * gen(arg){console.log(arg);let one = yield 111;console.log(one);let two = yield 222;console.log(two);let three = yield 333;console.log(three);}//執行獲取迭代器對象let iterator = gen('AAA');console.log(iterator.next());//next方法可以傳入實參console.log(iterator.next('BBB'));console.log(iterator.next('CCC'));console.log(iterator.next('DDD'));生成器函數,不但可以控制流程順序,其實也是可以帶入參數的;其參數是上一個迭代函數執行成功以后的返回值,如上圖所示;
總結
以上是生活随笔為你收集整理的为什么使用ES6生成器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 王者荣耀排位胜场分怎么加 《王者》在线观
- 下一篇: 迭代器自定义遍历对象