Home > other >  How to return promise with modifications from async function?
How to return promise with modifications from async function?

Time:04-14

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?

CodePudding user response:

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.

  • Related