0
GetNextdaySchoolMeal():Array<string>{
    fetch(this.GetLink())
      .then((response) => {
        return(response.json());
      })
      .then((response) => {
        return(response.mealServiceDietInfo[1].row[0].DDISH_NM.split("<br/>"));
      })
      .catch(function(error){throw new Error(error);});
  }
error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

this.GetLink() returns the API link for the next weekday. Why can't the response.mealServiceDietInfo[1].row[0].DDISH_NM.split("<br/>") in the second then callback be returned from GetNextdaySchoolmeal?

If I put console.log instead of return in the seventh line and delete the type in the first line, it will work as expected. However, I expect that the function returns an array.

Lauren Yim
  • 12,700
  • 2
  • 32
  • 59
kdh8219
  • 7
  • 2
  • I think its because of you using fetch. I dont know how familiar you are with async/await. But fetch will always return a Promise object. If you want to get that outside the Promise scope , i think just create an empty variable above this function and assign it inside the .then() – user655941 Apr 03 '22 at 10:07
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Lauren Yim Apr 03 '22 at 10:16
  • Hi, welcome to Stack Overflow! I've edited your question to better clarify what ‘Why can't seconds then's return be return’ means (if I've gotten this wrong, please feel free to [edit] your question). Even though I've already answered this question, I've realised that it's the same question as the one linked above — how to work with promises/async APIs. – Lauren Yim Apr 03 '22 at 10:19

1 Answers1

2

First, fetch returns a promise. GetNextdaySchoolMeal should return Promise<Array<string>>.

Once you've fixed that, you need to return the promise. Add a return before fetch:

GetNextdaySchoolMeal(): Promise<Array<string>> {
  return fetch(this.GetLink())
    .then((response) => {
      return(response.json());
    })
    .then((response) => {
      return(response.mealServiceDietInfo[1].row[0].DDISH_NM.split("<br/>"));
    })
    .catch(function(error){throw new Error(error);});
}

More information on asynchronous functions and promises:

Lauren Yim
  • 12,700
  • 2
  • 32
  • 59