我有一个异步生成函数(批处理作业),随着时间的推移,它变得相当大,我想把它拆成多个函数。
async *execute(): AsyncGenerator<ISyncState> {
await doThis();
await doThis2();
await doThis3();
yield "this";
await doThis4();
await doThis5();
await doThat();
yield "that";
// .. many more functions
}
async doThis() {...}
async doThat() {...}
async doThis2() {...}
呼叫者。
const gen = execute();
for await (const syncState of gen)
// do something
我想把它变成:
async *execute(): AsyncGenerator<ISyncState> {
await step1();
await step2();
await step3();
}
async step1() {
await doThis();
yield "this1"; <-- doesn't work
await doThis2();
yield "this2"; <-- doesn't work
await doThis3();
yield "this3"; <-- doesn't work
}
有沒有辦法在 "step1() "的範圍內產生出來呢(最好的解決方法是什麼?)
就像在普通的生成器中一样,你可以使用 yield*
在一个异步生成器内产生一个子生成器,即使子生成器也是异步的。
const doThis = () => Promise.resolve();
async function* execute() {
yield* step1();
// await step2();
// await step3();
}
async function* step1() {
await doThis();
// await doThis2();
// await doThis3();
yield "this";
}
(async () => {
for await (const item of execute()) {
console.log(item);
}
})();
你让你的 "步骤 "自己成为异步生成器. 就像这样。
async function *step1() {
yield await step1a();
yield await step1b();
yield await step1c();
}
然后你可以这样说,使用 for await...of
:
async function *execute() {
for await ( item of step1() ) {
yield item;
}
for await ( item of step2() ) {
yield item;
}
for await ( item of step3() ) {
yield item;
}
. . .
}