简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM