Method chaining with async/await in TypeScript

前端 未结 1 1092
再見小時候
再見小時候 2021-01-05 12:36

I have a situation where I need to call an async method on the result of an async method.

class Parent {
  constructor(private child: Child) { }

  private          


        
1条回答
  •  醉梦人生
    2021-01-05 13:08

    Is there a way to design my API better so that users won't need the double await? Even if it means changing the structure of my example drastically.

    You must not make getResult asynchronous, it needs to return a Result instance right away so that further methods can be called on it. Your example is a bit weird since getChild doesn't really need to be asynchronous at all. But lets assume it is, and does some important.

    You then could write

    class Parent {
      private async getChild(): Promise {
        … // whatever
      }
    
      getResult(): Result {
         return new Result(this.getChild())
      }
    }
    class Result {
      constructor(p: Child) {
        this.promise = p;
      }
      async getText(): Promise {
        return (await this.promise).getText();
      }
    }
    

    Now you can call parent.getResult().getText() directly. Basically, Result acts as a proxy wrapper around the Child class that does both the awaits. Maybe in your actual architecture you can even avoid the this.promise and do the child and text accesses in one step.

    However, usually this is not worth it. Just let your caller await each step.

    0 讨论(0)
提交回复
热议问题