Sunday, 9 April 2017

Return variable in Node.js

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.



via maxnar

No comments:

Post a Comment