模仿async,用Generator函数实现
async function fn(args) {
// ...
}
// 等同于
function fn(args) {
return spawn(function* () {
// ...
});
}
实现spawn函数,async函数会返回一个Promise对象
function spawn (genF) {
return new Promise(function (resolve, reject) {
let gen = genF();
function execute (nextF) {//执行Generator函数
let next;
try {
next = nextF()
} catch (e) {
reject(e);
}
if (next.done) {
return resolve(next.value);
}
Promise.resolve(next.value).then(
function (v) {
execute(function () {
return gen.next(v)
})
},
function (e) {
execute(function () {
return gen.throw(e)
})
})
}
execute(function () {
return gen.next(undefined);
})
});
}