Hector Hinojosa Hector Hinojosa - 3 months ago 9
Javascript Question

Node variable scope

So this seems like a basic thing but has caused extra work on my end this week several times. How do I define a variable within a function and make it available outside of said function.

var variables = { initial: 'To Start'};
var curl = require('curlrequest');


var options = {
url: 'www.google.com',
verbose: true,
stderr: true
};

curl.request(options, function (err, data) {
variables.testing123 = function() {return 'woking now';};
variables.ting123 = 'I should be showing in console';
});

console.log(variables);


Console Output:

{ initial: 'To Start' }


The goal is to curl a url and store the returned json into a varialble to be used in another function to sort out highest resolution and build a download list from the available data. The latter part of the script is ready and but in order to dynamically do this I need to curl several urls and filter the json for each.

Answer

The function you pass to curl.request is evaluated asynchronously, so anything you want to run after the request finishes needs to go into that function.

var curl = require('curlrequest');
var variables = { initial: 'To Start'};
var options = {
   url: 'www.google.com',
   verbose: true,
   stderr: true
};

curl.request(options, function (err, data) {
   variables.testing123 = function() {return 'woking now';};
   variables.ting123 = 'I should be showing in console';
   console.log(variables);
});

If you have a bunch of requests to process, you can use promises, or do something like this:

curl.request(options1, process);
curl.request(options2, process);
curl.request(options3, process);
var requestsProcessed = 0;
var results = [];
function process(err, data) {
    results.push(data);
    requestsProcessed++;
    if (requestsProcessed === 3) {
        // do something
    }
}