Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return promise with modifications from async function?

I have an async function and I need to do the following in this function:

  • If ajaxRequest succeeds then I must process value and return it in Promise,
  • Otherwise return Promise with null.

This is what I did:

 public async foo(): Promise<B> {
    const promiseA: Promise<A> = ajaxRequest(...);
    promiseA.then((a) => {
      return new Promise<B>((resolve) => {
         const b: B = process(a); 
         resolve(b);
      })
    });
    promise.catch(e => {
      console.error(e);
      return new Promise<B>((resolve) => {
         resolve(null);
      })
    })
  }

And I get A function whose declared type is neither 'void' nor 'any' must return a value. compilation error. Could anyone say how to do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your function seems to simplify to

class Something {
  public async foo(): Promise<B | null> {
    try {
      const a = await ajaxRequest(...);
      return process(a);
    } catch (e) {
      console.error(e);
      return null;
    }
  }
}

assuming process returns B.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading