I'm currently trying to write a simple little node module to make it easier accessing an API. The problem I'm experiencing is that I'd like to be able to call
var randomVar = myModule.function()
and assign the output of that function to the variable. I believed it to be as easy as returning the value in question, but randomVar stays undefined and I'm clearly missing something here.
This is the HTTP request I have, which seems to be rather standard:
exports.function = function(){
var options = {
// stuff
};
fetchResult = function(options,callback){
var http = require('http');
var str = '';
http.get(options,function(res){
res.on('data',function(chunk){
str += chunk;
});
res.on('end',function(){
callback(JSON.parse(str));
});
}).on('error', function(e){
callback(e.message);
});
}
fetchResult(options,function(data){
console.log(data);
// what do I do here?
});
}
The console.log at the bottom outputs the data I want, but what exactly would I do with this to be able to assign it to a variable outside the module?
Thank you so much in advance.
http.get()in your case). The data isn't simply ready yet when the function returns. See tymeJV's callback recommendation (answer below) as the usual solution for this issue.