0

i need help with getting data outside the fetch function.

const  getSpecies =  (URL) => {
    fetch(URL)
    .then(response => response.json())
    .then(data =>{
        console.log(data.name);
    })
}

I'm fetching data from API to get a one value. I don't know how return this value as a value of function. Always I get a undefined or [Promise object]. I tried like that:

const  getSpecies = async (URL) => {
    const  data = await fetch(URL);
    const  resoult = await data.json();
    const species = resoult.name;
    console.log(species);// value of name
    return species
}

I also tried use few callbacks functions and return in all places.

I still have problems with understand asynchronous JS. That's why I need help.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

async-await always returns a promise, even when it returns nothing.

Where ever you use getSpecies() function do a .then() after it to get data.

getSpecies.then(data=>{console.log(data)})

And in the first case you have already done correctly. You simply need to return the data :)

const  getSpecies =  (URL) => {
    fetch(URL)
    .then(response => response.json())
    .then(data =>{
        console.log(data.name); // This should get the data here and you can return it here
       return data;
    })
}

If your URL is responding correctly, then the above code should work correctly.

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35