-1

I want to return a some information in a json format so I can assign variables to them. I'm using Axios to get some json info on movies but can't seem to assign a variable to the data, as I always get 'undefined' in the output. Any fixes?

Here's my code, as you can see I'm trying to return something from the function then assign a value to it.

function getMovie(movie){
    axios.get('http://www.omdbapi.com?t='+movie+'&apikey='+APIKEY)
        .then((response) => {
            console.log(response.data);
            let info = response.data;
            return response.data;
        })
        .catch((error)=>{
            console.log(error);
        })
};

let movieInfo = getMovie('Dune');
console.log(movieInfo);
yvirdi
  • 171
  • 1
  • 1
  • 3
  • You sure api key working? What your console status? got `error log` or `undefined`? – Kerry Feb 21 '22 at 02:48
  • it works fine with the console.log(response.data) statement, but when I try logging movieInfo, it returns undefined. – yvirdi Feb 21 '22 at 02:50
  • 1
    `getMovie('Dune').then(console.log)`. Also `return axios.get(...` – danh Feb 21 '22 at 02:52
  • do you wrapper the ```let movieInfo = getMovie('Dune'); console.log(movieInfo);``` into a function? – Anh Le Feb 21 '22 at 03:00

1 Answers1

-1
function getMovie(movie){
    let answer =  axios.get('http://www.omdbapi.com?t='+movie+'&apikey='+APIKEY)
        .then((response) => {
            console.log(response.data);
            let info = response.data;
            return response.data;
        })
        .catch((error)=>{
            console.log(error);
        })
     return answer
};

let movieInfo = getMovie('Dune');
console.log(movieInfo);
Kerry
  • 384
  • 3
  • 25
  • 1
    `console.log(movieInfo);` will log the promise produced by `get`, not the result. – danh Feb 21 '22 at 03:02
  • @danh pretty sure it will return the `response.data` into `answer` since the promise is solved by the `.then` block – Kerry Feb 21 '22 at 03:04
  • 1
    The promise is returned immediately and assigned to `answer`. That answer is returned immediately and assigned to `movieInfo`. console log will log that promise. Some time later, the the `then` block is executed, resolving the promise that was logged earlier. – danh Feb 21 '22 at 03:07
  • @danh You are right :) . I am sad that I am wrong. I been using Axios for more than 1 year – Kerry Feb 21 '22 at 03:15
  • You may have been using the more modern syntax, where you'd say `let answer = await get(...`. This nicer way to write it leaves one with the impression that async is solved -- that's why I think it's worthwhile to get the hang of promises using `.then`, `.catch` and `Promise.all()` – danh Feb 21 '22 at 03:22