2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
The asynchronous use of ES6 Generator functions is mainly achieved by using them in conjunction with Promises. This pattern is called the "thunk" pattern, and it allows you to write asynchronous code that looks synchronous.
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
function* asyncGenerator() {
console.log("Start");
yield delay(1000); // 等待1秒
console.log("After 1 second");
yield delay(1000); // 再等待1秒
console.log("After another second");
return "Done";
}
let gen = asyncGenerator();
function runGenerator(g) {
let result = g.next();
result.value.then(() => {
if (!result.done) {
runGenerator(g);
}
});
}
runGenerator(gen);
// 假设我们有以下 async generator
async function* asyncGen() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
// 我们可以使用 for...of 循环和 async...await 语法糖来简化调用
(async () => {
for await (let value of asyncGen()) {
console.log(value); // 依次输出 1, 2, 3
}
})();
function* asyncGenWithError() {
try {
yield Promise.reject("Error occurred!");
} catch (e) {
console.log(e); // 输出:Error occurred!
}
}
let genWithError = asyncGenWithError();
genWithError.next().value.catch(err => console.log(err));
function* innerAsyncGen() {
yield Promise.resolve("A");
yield Promise.resolve("B");
}
function* outerAsyncGen() {
yield "Start";
yield* innerAsyncGen(); // 委托给另一个异步 Generator 函数
yield "End";
}
let outerGen = outerAsyncGen();
function runOuterGenerator(g) {
let result = g.next();
result.value.then(val => {
if (!result.done) {
runOuterGenerator(g);
}
});
}
runOuterGenerator(outerGen);