0

We have a common code pattern in our typescript code base:

  public async publish(event: myEvent, myStr: string): Promise<void> {
    return new Promise<void>(async (resolve, reject) => {
      try {
        await this.doCoolStuff(event, myStr);
        return resolve();
      } catch (error) {
        return reject(error);
      }
    });
  }

Looking to simplify the code to not repeat most of that body, so that it looks something in the ballpark of:

  public async publish(event: myEvent, myStr: string): Promise<void> {
    return new HelperOfSomeSort() {
      this.doCoolStuff(event, myStr);
    }
  }

Is this possible?

GaTechThomas
  • 5,421
  • 5
  • 43
  • 69
  • Whats the point of all that code? Just call and return `this.doCoolStuff(event, myStr);`. – tkausl Mar 01 '19 at 20:12
  • How do you deal with exceptions if you don't have the try/catch? – GaTechThomas Mar 01 '19 at 20:29
  • You can catch the exceptions directly on the promise when you call it: `doCoolStuff(params).then(res => whatever()).catch(err => console.log(err))` – Jimmy Hedström Mar 01 '19 at 20:37
  • I found some good background info at the following SO question. Going to have to do some testing. https://stackoverflow.com/questions/42453683/how-to-reject-in-async-await-syntax – GaTechThomas Mar 02 '19 at 01:52
  • This seems to be the go-to for the topic... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises – GaTechThomas Mar 04 '19 at 15:09

1 Answers1

0

I think the new Promise is useless since the doCoolStuff is will return a promise. For the catch part then call the reject, the await will pass the erreur to the publish promise.

public async publish(event: myEvent, myStr: string): Promise<void> {
    return await this.doCoolStuff(event, myStr);
}

AP inc.
  • 156
  • 11