Generator 函數是協程在 ES6 的實現,最大特點就是可以交出函數的執行權(即暫停執行)參考鏈接:http://www.ruanyifeng.com/blog/2015/04/generator.html{ // genertaor基本定義 有一個星號有一個yield let tell = ... ...
{ // 長輪詢 let ajax=function* (){ yield new Promise(function(resolve,reject){ setTimeout(function () { resolve({code:0}) }, 200); }) } let pull=function(){ let genertaor=ajax(); let step=genertaor.next(); step.value.then(function(d){//step.value就是promise實例 if(d.code!=0){ setTimeout(function () { console.info('wait'); pull() }, 1000); }else{ console.info(d); } }) } pull(); }
Generator 函數是協程在 ES6 的實現,最大特點就是可以交出函數的執行權(即暫停執行)
參考鏈接:
http://www.ruanyifeng.com/blog/2015/04/generator.html
{ // genertaor基本定義 有一個星號有一個yield let tell = function*() { yield 'a'; yield 'b'; return 'c' }; let k = tell(); console.log(k.next()); // {value: "a", done: false} console.log(k.next()); // {value: "b", done: false} console.log(k.next()); // {value: "c", done: false} console.log(k.next()); // {value: undefined, done: true} } { let obj = {}; obj[Symbol.iterator] = function*() { yield 1; yield 2; yield 3; } for (let value of obj) { console.log('value', value); // 1 2 3 } } { let state = function*() { while (1) { yield 'A'; yield 'B'; yield 'C'; } } let status = state(); console.log(status.next()); //{value: "A", done: false} console.log(status.next()); //{value: "B", done: false} console.log(status.next()); //{value: "C", done: false} console.log(status.next()); //{value: "A", done: false} console.log(status.next()); //{value: "B", done: false} } // { //需要一些插件才能實現,結果跟上面一樣 // let state=async function (){ // while(1){ // await 'A'; // await 'B'; // await 'C'; // } // } // let status=state(); // console.log(status.next()); // console.log(status.next()); // console.log(status.next()); // console.log(status.next()); // console.log(status.next()); // } { let draw = function(count) { //具體抽獎邏輯 console.info(`剩餘${count}次`) } let residue = function*(count) { while (count > 0) { count--; yield draw(count); } } let star = residue(5); //次數後臺傳 let btn = document.createElement('button'); btn.id = 'start'; btn.textContent = '抽獎'; document.body.appendChild(btn); document.getElementById('start').addEventListener('click', function() { star.next(); }, false) }