Reputation: 87
I'm building a little framework with Node.js, and I would try to use data from an API but I don't know why it doesn't work (asynchronous but ??).
var request = require('request');
var IndexController = function(request, parameters) {
this.request = request;
this.parameters = parameters;
}
IndexController.prototype.execute = function () {
var url = "https://prod.api.pvp.net/api/lol/euw/v1.1/champion?api_key=#my-private-key";
var data;
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
data = JSON.parse(body);
}
});
return data;
}
module.exports = IndexController;
Some advices could be very great ! By the way, I tried with xmlhttprequest too.
Thanks for your help !
Upvotes: 0
Views: 94
Reputation: 637
Basically, if you would return data there, it would be empty. That is because of the asynchronous function handling of Node.js. (The function-call 'request(url,...)' is executed in the "same" time, as the returning of the variable 'data').
Look at the above mentioned request-function: it receives a callback function, containing all the logic that will be executed, once the function is done.
What you need for a start is the following; add a callback-function argument:
IndexController.prototype.execute = function (callbackFunc) {
// do request as you intended
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
data = JSON.parse(body);
callbackFunc(data); // then call callback-function with results
}
});
In the calling part of your logic, where IndexController is instantiated and 'IndexController.execute()' is called, you then call it with your callback-function as argument (ie. what should be done with the result):
var controller = IndexController(req, params);
controller.execute(function (data) {
console.log(data);
});
Hope that does for a start.
Upvotes: 1