Search code examples
javascriptjsonnode.jsnpmrequestjs

Assign requestjs response to variable


How would one assign the body of request.get('http://someurl/file.json', function(err, response, body) {}) to a variable?

For example:

file.json

{
    "Name1": {
        "prop": "value"
    },
    "Name2": {
        "prop": "value"
    }
}

app.js

var json = request.get(http://localhost/file.json);
json = JSON.parse(json);

console.log(json["Name1"].prop);

Thanks in advance :)


Solution

  • var myvariable1;
    
    request.get('http://someurl/file.json', function(err, response, body) {
        myvariable1=response.Name1.prop;
    })
    

    the body is not available until the callback is complete. I don't think there is any shorthand for callbacks that allows what you want. However, there is a shorthand for promises. You could use the bluebird npm module to try and promisify this. You could then do ... myvar = request.get('path'); .... myvar would then contain the result of the resolved promise ON resultion (not before) - this works in an AngularJS environment for sure and prob would work in pure Node too - Hope that gives some food for thought.

    You could also use something like the q library to promisify this (which I believe is now in Node by default).

    function getMyData() {
        var def=q.defer();
        request.get('http://someurl/file.json', function(err, response, body) {
            def.resolve(response.Name1.prop);
        })
        return def.promise();
    }
    
    // myvar will have the result of the resolution on resolution (not before)
    var myvar = getMyData();
    
    // to test this approach you might want to use a settimeout to repeatedly dump the value of myvar every X ms.
    // Again this approach deffo works in Angular and hopefully works in Node too.
    

    Worse case scenario if this doesn't work then you resort COULD resort to ...

    var myvar;
    getMyData().then(function(data) {
      myvar = data;
    ));
    

    Which puts you back kinda where you started lol :)

    PS I have ignored error handling with promise CATCH blocks for the sake of simplicity