简体   繁体   English

TypeScript Async/Await 箭头函数:正确的语法(在 React 中)

[英]TypeScript Async/Await Arrow Function: Right Syntax (in React)

I have an arrow function, which compares two values.我有一个箭头函数,它比较两个值。 One value comes from another function, which gets the value from an API Endpoint.一个值来自另一个函数,该函数从 API 端点获取值。 I would like to use the await / async style instead of Promises (.then, .catch, .finaly).我想使用 await / async 样式而不是 Promises(.then、.catch、.finaly)。

In JavaScript it's easy peasy, but I have some Problems with TypeScript.在 JavaScript 中这很容易,但我在使用 TypeScript 时遇到了一些问题。 How to correctly write that function?如何正确编写该函数?

I have something like this (Pseudocode):我有这样的东西(伪代码):

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

With that code the IDE cries for the first line: Type '() => Promise' is missing the following properties from type 'Promise': then, catch, [Symbol.toStringTag]使用该代码,IDE 为第一行哭泣: Type '() => Promise' 缺少来自类型 'Promise' 的以下属性: then, catch, [Symbol.toStringTag]
While the compiler tells: Type 'Promise' is not assignable to type '() => Promise'.虽然编译器告诉:类型 'Promise' 不可分配给类型 '() => Promise'。 Type 'Promise' provides no match for the signature '(): Promise'.类型 'Promise' 与签名 '(): Promise' 不匹配。 TS2322 TS2322

I have the feeling my return type is wrong...我感觉我的返回类型是错误的...

Will the code wrap my isEqual value in a Promise?代码会将我的isEqual值包装在 Promise 中吗?
Can I avoid that both functions are async?我可以避免两个函数都是异步的吗?
What would be the right Syntax ?什么是正确的语法

Thank you in advance!先感谢您!

@VLAZ found the error and explained it well in the comments. @VLAZ 发现了错误并在评论中很好地解释了它。 I still wanted to post a version with the new changes.我仍然想发布一个包含新更改的版本。

I changed the first block of code to:我将第一个代码块更改为:

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

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

Reason (explained in the comments): compareValues holds a function that will produce a promise when called .原因(在评论中解释): compareValues 持有一个函数,该函数在调用时会产生一个承诺。 It's not an actual Promise itself.它本身并不是一个真正的 Promise。

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

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