【问题标题】:TypeScript Async/Await Arrow Function: Right Syntax (in React)TypeScript Async/Await 箭头函数:正确的语法(在 React 中)
【发布时间】:2021-02-11 19:41:20
【问题描述】:

我有一个箭头函数,它比较两个值。 一个值来自另一个函数,该函数从 API 端点获取值。 我想使用 await / async 样式而不是 Promises(.then、.catch、.finaly)。

在 JavaScript 中这很容易,但我在使用 TypeScript 时遇到了一些问题。如何正确编写该函数?

我有这样的东西(伪代码):

compareValues: Promise<boolean> = async () => {
   try {
      const value1 = false;
      const value2 = this.getValue2;

      const isEqual = (await value2) === value1;
      return isEqual;
   } catch (error) {
      throw error;
   }
}
getValue2 = async () => {
try {
   const value2 = await axios.get(url, config);
   const value2Data = await value2.data;

   return value2Data;
} catch (error) {
   throw error;
}
export interface IInterface {
   compareValues: () => Promise<boolean>;
}
const initialState: IInterface = {
   compareValues: () => {
      return Promise.resolve(false);
   }
}

使用该代码,IDE 会要求第一行:Type '() => Promise' is missing the following properties from type 'Promise': then, catch, [Symbol.toStringTag] 虽然编译器告诉:Type 'Promise' 不能分配给 type '() => Promise'。 类型“Promise”不匹配签名“(): Promise”。 TS2322

我感觉我的返回类型是错误的......

代码会将我的 isEqual 值包装在 Promise 中吗?
我可以避免这两个函数都是异步的吗?
什么是正确的语法?

提前谢谢你!

【问题讨论】:

  • compareValues: Promise&lt;boolean&gt; 应该是compareValues: () =&gt; Promise&lt;boolean&gt; - 毕竟compareValues 拥有一个函数,它会在被调用时产生一个promise。现在还不是真正的承诺。如果您需要 Promise 本身,则需要调用该函数。
  • 谢谢!这就是问题所在!我刚刚将 compareValues: Promise&lt;boolean&gt; = async () =&gt; { 更改为 compareValues = async () =&gt; { 并且它正在工作。

标签: reactjs typescript asynchronous async-await


【解决方案1】:

@VLAZ 发现了错误并在 cmets 中很好地解释了它。 我仍然想发布一个有新变化的版本。

我把第一段代码改成:

compareValues: = async () => {
   try {
      const value1 = false;
      const value2 = this.getValue2;

      const isEqual = (await value2) === value1;
      return isEqual;
   } catch (error) {
      throw error;
   }
}

原因(在 cmets 中解释):compareValues 拥有一个函数,该函数将在调用时产生一个承诺。这不是一个真正的 Promise 本身。

【讨论】:

    猜你喜欢
    • 2018-07-19
    • 2018-01-31
    • 1970-01-01
    • 2020-08-26
    • 2017-11-23
    • 2021-04-29
    相关资源
    最近更新 更多