// 定義Generator函數
function* simpleGenerator() {
debugger;
console.log('開始執行');
debugger;
yield '第一次暫停';
debugger;
console.log('恢復執行');
debugger;
yield '第二次暫停';
debugger;
console.log('結束執行');
debugger;
return '最終結果';
}
// 創建Generator對象
const gen = simpleGenerator();
debugger;;
// 逐步執行
console.log(gen.next()); // { value: "第一次暫停", done: false }
debugger;;
console.log(gen.next()); // { value: "第二次暫停", done: false }
debugger;;
console.log(gen.next()); // { value: "最終結果", done: true }
debugger;;
function* counterGenerator() {
debugger
let count = 0;
debugger
while (true) {
debugger
yield count++;
debugger
}
}
debugger
const counter = counterGenerator();
debugger
console.log(counter.next().value); // 0
debugger
console.log(counter.next().value); // 1
debugger
console.log(counter.next().value); // 2
debugger
function* interactiveGenerator() {
debugger
const name = yield '請輸入你的名字';
debugger
const age = yield `你好${name},請輸入你的年齡`;
debugger
return `${name}的年齡是${age}`;
}
debugger
const gen = interactiveGenerator();
debugger
console.log(gen.next()); // { value: "請輸入你的名字", done: false }
debugger
console.log(gen.next('張三')); // { value: "你好張三,請輸入你的年齡", done: false }
debugger
console.log(gen.next(25)); // { value: "張三的年齡是25", done: true }
debugger
// 模擬異步遞增
function asyncIncrement(num, delay) {
debugger
return new Promise(resolve => {
debugger
setTimeout(() => {
debugger
resolve(num + 1)
debugger
}, delay);
debugger
});
}
// Generator實現計數器
function* counter() {
debugger
let count = 0;
debugger
console.log('開始計數');
debugger
count = yield asyncIncrement(count, 1000);
debugger
console.log('計數:', count);
debugger
count = yield asyncIncrement(count, 1500);
debugger
console.log('計數:', count);
debugger
count = yield asyncIncrement(count, 800);
debugger
console.log('最終計數:', count);
debugger
return count;
}
// 簡化版執行器
function run(genFn) {
debugger
const iterator = genFn();
debugger
function step(value) {
debugger
const result = iterator.next(value);
debugger
if (!result.done) {
debugger
return result.value.then(step);
}
debugger
return Promise.resolve(result.value);
}
debugger
return step();
}
debugger;;
// 執行計數器
run(counter).then(finalCount => {
console.log('計數器停止於:', finalCount);
});