// Generator函数的自动执行器
// 简易版写法
function spawn(genF) {
return new Promise(function(resolve, reject) {
const gen = genF();
function step(data) {
const next = gen.next(data);
if (next.done) return resolve(next.value);
Promise.resolve(next.value).then(step).catch(reject);
};
step();
});
};
// 复杂版,考虑错误捕获
function spawnEx(genF) {
return new Promise(function(resolve, reject) {
const gen = genF();
function step(nextF) {
let next;
try {
next = nextF();
} catch (e) {
return reject(e);
};
if (next.done) {
return resolve(next.value);
};
Promise.resolve(next.value).then(function(v) {
step(function() { return gen.next(v); });
}, function(e) {
step(function() { return gen.throw(e); });
});
};
step(function() { return gen.next(undefined); });
});
}
async function wait(ms) {
return new Promise((res, rej) => {
setTimeout(() => {
res(new Date().valueOf());
}, ms);
});
}
spawnEx(function* () {
var a = yield wait(1000);
var b = yield wait(2000);
return `第一种:${b-a}ms`;
}).then(v => {
console.log(v);
}).catch(e => {
console.log(e);
});
spawnEx(function* () {
var a = wait(1000);
var b = wait(1000);
var c = yield a;
var d = yield b;
return `第二种:${d-c}ms`;
}).then(v => {
console.log(v);
}).catch(e => {
console.log(e);
});
// const gen = testGen();
// console.log(JSON.stringify(gen.next(undefined)));
// console.log(JSON.stringify(gen.next(123)));
// console.log(JSON.stringify(gen.next(100)));
console