Reputation: 10560
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
Reputation: 40444
Your script is executed in this order:
request()
is executedconsole.log(data)
request()
callback function, where you asign data
a valueIf 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
Reputation: 140
This is classic async confusion : your console.log
call will happen before the http request callback.
Upvotes: 2