自己有幸在《深刻了解 ES6》中看到如何通过自行封装生成器来执行异步工作,是它同步运行。
源码如下:
function* queryInfo() {const res1 = yield new Promise((res, rej) => {res(200);
});
console.log({res1});
try{const res2 = yield new Promise((res, rej) => {rej(403);
});
console.log({res2});
}catch(e){console.log("res2 谬误:", e)
}
const res3 = yield new Promise((res, rej) => {res(304);
});
console.log({res3});
}
function run(gnFn) {
// 创立迭代器
const gn = gnFn();
// 开启迭代
let res = gn.next();
(function step() {if (!res.done) {const promise = Promise.resolve(res.value);
promise.then(value => {res = gn.next(value);
step();}).catch(e => {res = gn.throw(e);
step();})
}
})()}
run(queryInfo); // {res1: 200} res2 谬误:403 {res3: 304}