简体   繁体   中英

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. I would like to use the await / async style instead of Promises (.then, .catch, .finaly).

In JavaScript it's easy peasy, but I have some Problems with 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]
While the compiler tells: Type 'Promise' is not assignable to type '() => Promise'. Type 'Promise' provides no match for the signature '(): Promise'. TS2322

I have the feeling my return type is wrong...

Will the code wrap my isEqual value in a 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. 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 . It's not an actual Promise itself.

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