Seong Lee
Seong Lee

Reputation: 10560

node.js - making result available globally (Request module)

I'm trying to process the returned JSON result from the request so I need to expand its scope outside this request call. To do that I declared data variable with an empty string and assign the result to this data but it doesn't print the result.

How can I accomplish this?

module.exports = function(callback) {

    var request = require("request")
    var url = "http://sheetsu.com/apis/94dc0db4"
    var data = "";

    request({
        url: url,
        json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            callback(body)

            data = body;

        }
    })

    console.log(data);


}

Upvotes: 0

Views: 54

Answers (2)

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

Your script is executed in this order:

  1. request() is executed
  2. console.log(data)
  3. request() callback function, where you asign data a value

If you want to print data, you must do it inside the request callback function. The async module, is very useful when performing async tasks, specially if you need to perform tasks in a specific order and use the data from this requests.

Upvotes: 1

Julien Cabanès
Julien Cabanès

Reputation: 140

This is classic async confusion : your console.log call will happen before the http request callback.

Upvotes: 2

Related Questions