0

I m trying to pull out a json from a function in a node.js script but nothing works

Here is the sample:

function parseJson()
{
    return req =  request(url, function(error,response,body)
    {
        var json = JSON.parse(body);
        console.log(json);
    });     
}

The console.log json is working but I want to be able to call this json outside of this function, in another function for example.

Thanks for your help

Chuug
  • 27
  • 10
  • You need to invoke that `another function` with this json as argument – gurvinder372 Apr 14 '16 at 12:27
  • @gurvinder372, Is `return req = request` appropriate ? – Rayon Apr 14 '16 at 12:29
  • @RayonDabre I guess it wll only return the `request` object. But it may depend on which module OP is using for making a REST call – gurvinder372 Apr 14 '16 at 12:31
  • Return the request directly isn't working and invoke another function in this function doesn't look clean. I want to re use this function to parse json from differents api – Chuug Apr 14 '16 at 12:33

2 Answers2

0

You could store the json in a variable with a wider scope. Or pass the parseJson a callback function, which will in turn use the JSON like so.

function parseJson(callback)
{
    return req =  request(url, function(error,response,body)
    {
        var json = JSON.parse(body);
        callback(json);
    });     
}

You could also return a promise (I assume that's what your request method does), and attach a .then() call to said promise, again passing it a callback.

GMchris
  • 5,439
  • 4
  • 22
  • 40
0

When you make an http request in node.js, it executes asynchronously. In node.js most functions that execute asynchronously take a callback parameter as its last parameter. A callback is a function that executes when the request has finished. The parameters of that function usually take the form of (error, result).

So your callback function should first check for an error and then process the result. Because you need to use callbacks in node.js, you can't just return values directly like you would with a synchronous function. The result will always be a parameter in your callback function. Example:

var request = require('request');

function parseJson(callback) {

    request('https://www.yourapi.com', function (error, response, body) {
        if(error) {
            callback(error, null);
        } else {
            var parsed = JSON.parse(body);

            callback(null, parsed);
        }
    });

}

parseJson(function(error, parsedJson) {
    if(error){
        /* do something with the error */
    } else {
        console.log(parsedJson);
    }
});

This is a very common pattern in node.js and is explained well in this answer. Using Promises is another solution.

Community
  • 1
  • 1
Cuthbert
  • 2,908
  • 5
  • 33
  • 60