簡單說說JavaScript的Generator 實現(ES6)


Generator 是 ES6 中新增的語法,和 Promise 一樣,都可以用來異步編程

// 使用 * 表示這是一個 Generator 函數 // 內部可以通過 yield 暫停代碼 // 通過調用 next 恢復執行 function* test() { let a = 1 + 2; yield 2; yield 3; } let b = test(); console.log(b.next()); // > { value: 2, done: false } console.log(b.next()); // > { value: 3, done: false } console.log(b.next()); // > { value: undefined, done: true }

從以上代碼可以發現,加上 * 的函數執行后擁有了 next 函數,也就是說函數執行后返回了一個對象。每次調用 next 函數可以繼續執行被暫停的代碼。以下是 Generator 函數的簡單實現

// cb 也就是編譯過的 test 函數 function generator(cb) { return (function() { var object = { next: 0, stop: function() {} }; return { next: function() { var ret = cb(object); if (ret === undefined) return { value: undefined, done: true }; return { value: ret, done: false }; } }; })(); } // 如果你使用 babel 編譯后可以發現 test 函數變成了這樣 function test() { var a; return generator(function(_context) { while (1) { switch ((_context.prev = _context.next)) { // 可以發現通過 yield 將代碼分割成幾塊 // 每次執行 next 函數就執行一塊代碼 // 並且表明下次需要執行哪塊代碼 case 0: a = 1 + 2; _context.next = 4; return 2; case 4: _context.next = 6; return 3; // 執行完畢 case 6: case "end": return _context.stop(); } } }); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM