0

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!

2
  • 3
    compareValues: Promise<boolean> should be compareValues: () => Promise<boolean> - after all compareValues holds a function that will produce a promise when called. It's not an actual promise right now. If you instead need the promise itself, then you need to call the function. Commented Oct 29, 2020 at 11:06
  • 1
    Thank you! That was the problem! I just changed compareValues: Promise<boolean> = async () => { to compareValues = async () => { and it's working. Commented Oct 29, 2020 at 11:16

1 Answer 1

1

@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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.