-1

I'm stuck with a function that is supposed to fetch data from an API and then return an array of a predefined type. However, I would always get an error message indicating that A function whose declared type is neither 'void' nor 'any' must return a value.

I don't really understand why this message shows up since I have a return-statement in my function, even if an error occurs while fetching the data:

export async function queryOpenCage(query: string): Promise<MarkerPoint[]> {
  const {opencageApiKey}: ClientSettings = JSON.parse(
    document.getElementById(ElementID.Settings)!.textContent!
  )
  const fetchURL = `https://api.opencagedata.com/geocode/v1/json?key=${opencageApiKey}&q=${query}&limit=5&pretty=1`
  const resultItems: MarkerPoint[] = []
  fetch(fetchURL)
    .then(response => {
      return response.json()
    })
    .then(json => {
      const items = json.results.map((res: any) => {
        return {
          lat: res.geometry.lat,
          lng: res.geometry.lng,
          address: res.formatted
        }
      })
      return resultItems.push(...items)
    })
    .catch(error => {
      return []
    })
}

Any help or suggestions are highly appreciated!

Pascal
  • 77
  • 1
  • 11
  • Well there's no `return` in your function. You do use `return` in the promise chain callbacks, but you never return the promise built by the promise chain. – Bergi Sep 25 '20 at 13:05
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Krzysztof Krzeszewski Sep 25 '20 at 13:06
  • 1
    Be careful as `resultItems.push(...items)` returns the new length of the array, not the array itself, therefore `return resultItems.push(...items)` will return a number rather than the array you are expecting. You should simply have `resultItems.push(...items);` in your `then` block and `return resultItems;` after the `catch` block – secan Sep 25 '20 at 13:18
  • thanks a lot @secan, this did the job for me :) – Pascal Sep 25 '20 at 13:22
  • If you're going to mark your function as `async`, then use `await` on your promises so you can then return the final value from the function itself (which will become the resolved value of the `async` function). If not, then return the top level promise from your function and make sure all child promises are properly chained and return their promise or data. Basically, this code is a mess as you've mixed two methods of handling multiple asynchronous operations and not followed the proper technique for either one. – jfriend00 Sep 25 '20 at 14:58
  • @jfriend00 thanks, I see now that I've indeed mixed up two concepts! It's all a bit confusing if you do it for the first time – Pascal Sep 25 '20 at 16:31

1 Answers1

0
fetch(fetchURL)

should be

return fetch(fetchURL)
PatricNox
  • 3,306
  • 1
  • 17
  • 25