-1

I'm trying to collect some JSON data from an URL and wold like to use the data throughout my Node.js app. In the code below, the JSON is collected properly but the variable partOfJson comes back as undefined. I guess it's because the function getTheData returns the theData before it's finished.

function getTheData() {

    const request = require('request'),url = 'myURL';

    request(url, (error, response, body)=> {
            var theData = JSON.parse(body);
    });

    //Do stuff with theData

    return theData;
};




//Somewere else
var partOfJson = getTheData();  //I want partOfJson to be parts of the collected JSON

Does anyone know how to solve this? I just starting learning about Node.js so please go easy on me.

2
  • Just add the return where you are assigning "var theData=" Commented Apr 9, 2017 at 12:16
  • This question has been asked about a hundred times. You can't return data which hasn't come yet, It also has nothing whatsoever to do with node.js. Commented Apr 9, 2017 at 13:02

1 Answer 1

-1

Yes, it is happening because of the asynchronous nature, you can use the callback and return the theData in the callback, or you can use the promises to get the value.

For callback:

function getTheData(cb){
                 //get data from your url and store it in theData variable
                 cb(theData)
                }

and you can access it by calling the function as below:

 getTheData(function(data){
            partOfJson=data
            }

This way partOfJson won't be undefined

OR you can go the promises way, here is the link to get you started https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.