-2

I am doing a simple api get request, but I can't seem to isolate the array on its own. its always inside of a promise and I'm not sure how to remove it or how to access the values stored in the array.

function getLocation(name) {

  let output = fetch(`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=oqAor7Al7Fkcj7AudulUkk5WGoySmEu7&q=london`).then(data => data.json());
  return output

}

function App() {

  var output = getLocation(`london`);
  console.log (output)
...
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(3)

is what is displayed in the console.log I require just the Array(3)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
blujay
  • 19
  • 6
  • 3
    Possible duplicate of [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) – ponury-kostek May 16 '19 at 15:39

1 Answers1

3

fetch, and Promise#then, always return a promise. To access the information it fetches, consume the promise:

getLocation()
.then(data => {
    // use the data
})
.catch(error => {
    // Handle/report the error
});

or in an async function:

const data = await getLocation();

Side note: Your getLocation has a very common error (so common I wrote it up on my anemic little blog): It doesn't check that the HTTP operation succeeded. fetch only fails on network errors, not HTTP errors. To fix it:

function getLocation(name) {
    return fetch(`http://dataservice.accuweather.com/locations/v1/cities/search?apikey=oqAor7Al7Fkcj7AudulUkk5WGoySmEu7&q=london`)
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error, status = " + response.status);
        }
        return response.json();
    });
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @TJCrowder this leads into another question, how do I take the .then(data => ... and set it to a variable that can be used outside of the function. – blujay May 16 '19 at 15:58
  • 1
    @blujay - Hi! You're not the only one with that question, people ask it a lot. :-) See the answers to [this question](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). The answers [here](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) may also be useful. Happy coding! – T.J. Crowder May 16 '19 at 16:13
  • @Daniel - Thanks!! Amazingly, I noticed I'd missed it as I typed it but then forgot to go back and fix it. – T.J. Crowder May 16 '19 at 16:15
  • @TJCrowder thanks, I'm still getting the hang of the => thing haha – blujay May 16 '19 at 16:15
  • @blujay - No worries! Just FWIW, it's not to do with the arrow function, it could be a traditional function and you'd have the same situation. – T.J. Crowder May 16 '19 at 16:16