這一篇是關於ES6中生成器函數相關總結和理解...vue
在阮一峯老師的書中的說法是:
Generator 函數有多種理解角度。語法上,首先能夠把它理解成,Generator 函數是一個狀態機,封裝了多個內部狀態。執行 Generator 函數會返回一個遍歷器對象,也就是說,Generator 函數除了狀態機,仍是一個遍歷器對象生成函數。返回的遍歷器對象,能夠依次遍歷 Generator 函數內部的每個狀態。ios
個人理解:
生成器函數能夠理解爲: 函數內部是由多個小函數組成的, 使用yield關鍵字將函數內部 分割成多個塊區域; 而且當函數執行時, 遇到yield就會中止, 而且將yield 後面的表達式結果輸出(固然外部要調用next()方法); 下次再調用next()方法時, 就從上一個中止的地方開始執行(這意味着函數有有記憶功能); 若是下面沒有再遇到yield的話 就像普通函數執行完. 函數的返回值是一個可迭代對象(遍歷器對象); 我喜歡叫可迭代對象, 或者說可遍歷對象...ajax
function CreateIterator(iterator) { // 定義一個初始下標用來判斷 let nextIndex = 0; // 返回對象: 包含的next方法, return { next: function () { // 返回一個對象: value是當前對象下標對應的值, done是是否遍歷完成 return nextIndex < iterator.length ? // i++ 先參數運算在 自增1 {value: iterator[nextIndex++], done: false} : {value: undefined, done: true}; } } } // 實例化一個遍歷器 let iter1 = CreateIterator([1,2,3,4,5]); console.log(iter1); // 一個具備next方法的對象 console.log(iter1.next().value); // 1 console.log(iter1.next().value); // 2 console.log(iter1.next().value); // 3 console.log(iter1.next().value); // 4 console.log(iter1.next().value); // 5 console.log(iter1.next().value); // undefined
generator生成器函數的使用: function *fn() { 代碼1; yield; 代碼2; } 普通函數: 執行到底 生成器函數: 遇到yield會暫停,交出執行權,下次執行從上次的中止的位置繼續 生成器函數返回值爲: 生成器對象 生成器對象.next()方法才能執行 函數體中的代碼 // 能夠解決函數回調嵌套的問題; 解決耗時操做 function *func() { // 請求數據. // yield ajax() // 處理數據 } // generator函數本質上 分割成多個小函數來執行... yield關鍵字先後 // 遇到yield就暫停; 沒有就往下執行... // yield 起到了 暫停函數執行的做用
舉個栗子:json
function *g2(x, y) { let sum = x+y; yield sum; // sum是第一個輸出結果 let agv = sum / 2; yield agv; // agv 是第二個輸出的結果 return {"和": sum, "平均數": agv}; // 最後一個結果 } let gg2 = g2(100, 20); console.log(gg2.next().value); // 120 console.log(gg2.next().value); // 60 console.log(gg2.next().value); // { '和': 120, '平均數': 60 }
這裏只作一個簡單舉例, 像咱們平時使用的ES7中的 async 函數; 他就是生成器函數的一種應用; 它實際上是 Generator 函數的語法糖。axios
借用ES6入門中的一個例子: 兩種方式去讀取文件數組
const fs = require('fs'); const readFile = function (fileName) { return new Promise(function (resolve, reject) { fs.readFile(fileName, function(error, data) { if (error) return reject(error); resolve(data); }); }); }; // 1.使用生成器函數 讀取文件 const gen = function* () { const f1 = yield readFile(__dirname + '/first.json'); const f2 = yield readFile(__dirname + '/second.json'); console.log(f1.toString()); // 沒有輸出; 由於 f1 拿到是一個 Iterator 對象 console.log(f2.toString()); }; // 使用 async + await 讀取; 注意兩種需配合使用 const asyncReadFile = async function () { const f1 = await readFile(__dirname + '/first.json'); const f2 = await readFile(__dirname + '/second.json'); console.log(f1.toString()); //async函數的返回值是 Promise 對象 console.log(f2.toString()); }; gen(); // 沒有值, 須要用 next()方法去取值 asyncReadFile() // 返回值 {"hello": "first"} {"hello": "second"}
因此; 咱們這裏對比一下; async函數是將 Generator 函數的星號(*)替換成async,將yield替換成await,大大方便了咱們的使用。異步
平時的異步代碼 咱們就可使用 async + await的形式來實現...
好比vue中的一個ajax請求去獲取數據async
methods: { async getApi() { let res = await axios.get('url') // 這裏的執行順序是同步的... console.log(res) } }