-1

I have an object that will hold other objects.

import Axios from "axios";

let API = {
    get:{
        dogPicture: () =>
        {   
            Axios.get("https://dog.ceo/api/breeds/image/random")
            .then(res => {
                //this.setState({wiseDog:res.data.message})
                //this.setState({isLoading:false})

            })
            .catch( err => {
                //this.setState({error:err.data.message})
            })
        },
        dogFact: () =>
        {
            Axios.get("/facts")
            .then( response => {
                //this.setState({DogFact:response.data.facts[0]})
                //this.setState({isLoading:false})
                return response.data.facts[0];
            })
            .catch( err => {
                console.log("still error", err)
                //this.setState({error:err})
                return err;
            })
        },
        test: () => "test"
    }
}  

export default API;

If I import that and call

let message = API.get.test();

It will return the string test. But If I try to return the res from my dogPictureor response from my dogFact, It returns undefined. If I try to console.log(res) it shows the correct expected value.

How can I return the value I get from res and response when calling those functions?

EAzevedo
  • 751
  • 2
  • 17
  • 46
  • 1
    Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. Wrapping your head around async programming will be pretty important. – Dave Newton Feb 04 '19 at 19:06
  • I'm amused that [dog.ceo](https://dog.ceo) is a thing. – tadman Feb 04 '19 at 19:07

1 Answers1

1

To put it simply, you can't. Javascript is an asynchronous language, and "test" is being returned in a synchronous fashion. Because you're involving remote API's, I recommend returning a promise (Adding async will turn your function into a promise, and allow you to use await):

import Axios from "axios";

let API = {
    get:{
        dogPicture: async () =>
        {   
            const res = await Axios.get("https://dog.ceo/api/breeds/image/random");

            return res.data;
        }
        test: () => "test"
    }
}  

export default API;

Then in your code, you can use:

let message = await API.get.dogPicture();
Blue
  • 22,608
  • 7
  • 62
  • 92