繁体   English   中英

如何通过异步 function 的修改返回 promise?

[英]How to return promise with modifications from async function?

我有一个异步 function,我需要在这个 function 中执行以下操作:

  • 如果 ajaxRequest 成功,那么我必须处理值并在 Promise 中返回它,
  • 否则返回 Promise 和 null。

这就是我所做的:

 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);
      })
    })
  }

我得到A function whose declared type is neither 'void' nor 'any' must return a value. 编译错误。 谁能说怎么做?

您的 function 似乎简化为

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

假设process返回B

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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