0

I am currently trying to get a JSON object out of a function. I can access all the data in the function, but I am struggling to get the data out so I can actually use the Data.

 var imdb = require('imdb');


imdb('tt4477536', function(err, data) {
  if(err)
    console.log(err.stack);

  if(data)
    console.log(data)
});

This works fine and I get the Data:

{ title: 'Fifty Shades Freed',
  year: '2018',
  contentRating: 'R',
  runtime: '1h 45min',
  description: 'Anastasia and Christian get married, but Jack Hyde 
continues to threaten their relationship.',
  rating: '4.4',
  poster: 'https://images-na.ssl-images-amazon.com/images/M/MV5BODI2ZmM5MzMtOWZiMC00ZGE3LTk3MWEtY2U0ZjE3ZWJlNDEzXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_UX182_CR0,0,182,268_AL_.jpg',
  genre: [ 'Drama', ' Romance', ' Thriller' ],
  director: 'James Foley',
  metascore: '31',
  writer: 'Niall Leonard' }

So now my question is how do I get the Data out of this function, so I can actually use the data somewhere else in the code? like if i need the title in a string?

thanking you in advance.

Thomas

  • 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) – Adam Jenkins Mar 02 '18 at 12:40

1 Answers1

0

You can just declare a variable outside it:

var imdb = require('imdb');
var imdbData = {};

imdb('tt4477536', function(err, data) {
  if(err)
    console.log(err.stack);

  if(data) {
    imdbData = data;
    console.log(data);
  }
});

But do mind that since this is an asynchronous function you should be using a callback or Promise to be safe when using tha data. For a better approach:

var imdb = require('imdb');

imdb('tt4477536', function(err, data) {
  if(err)
    console.log(err.stack);

  if(data) {
    doNext(data);
  }
});

function doNext(data) {
    //use the data
}
Giannis Mp
  • 1,291
  • 6
  • 13
  • Perfect, this is working as it should now. I just needed to give it a little time before it get populated. Thank you very much for your help. – Thomas Petersen Mar 02 '18 at 12:27
  • your edit worked like a charm, even though i am getting an error: Cannot read property 'contentRating' of undefined which i declared as var rated = data.contentRating Am still getting the data though just annoying with the error showing – Thomas Petersen Mar 02 '18 at 13:31
  • I would suggest reading https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call to get more familiar with the asynchronous nature of requests – Giannis Mp Mar 02 '18 at 13:40