【问题标题】:ES6: how to split an async generator function without losing yield abilityES6:如何在不失去屈服能力的情况下拆分异步生成器功能
【发布时间】:2020-09-04 22:16:23
【问题描述】:

我有一个异步生成器功能(批处理作业),随着时间的推移它变得相当大。 我想把它分成多个功能:

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()”中产生? (解决这个问题的最佳方法是什么?)

【问题讨论】:

    标签: javascript typescript asynchronous ecmascript-6 generator


    【解决方案1】:

    就像在普通生成器中一样,您可以在异步生成器中使用 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);
      }
    })();

    【讨论】:

      【解决方案2】:

      您使“步骤”本身成为异步生成器。像这样的:

      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;
        }
      
        . . .
      
      }
      

      【讨论】:

        猜你喜欢
        • 2023-01-18
        • 2017-10-07
        • 2018-05-02
        • 2014-07-12
        • 2015-01-04
        • 2015-08-08
        • 1970-01-01
        • 2019-03-07
        • 2015-05-01
        相关资源
        最近更新 更多