Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't this function returning a value?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading