2

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.

1
  • You can't return data from a function that gets that data from an asynchronous operation (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. Commented Mar 11, 2014 at 23:52

1 Answer 1

2

Well, the function you are trying to return from is an asynchronous function, so you'll have to wait for the operations to complete before using that variable. This is where callbacks come in!

In your exports.function add a parameter called callback

exports.function = function (callback) {

callback is the function that will use your data! So, from fetchResult run:

callback(data);

And now you would call and use this function:

myModule.function(function(data) {
    //console.log(data); //the data you want!
});
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, but I'm still rather new to understanding callbacks. I thought the callback function in fetchResult() already waited for the operations to complete seeing how the callback is called inside res.on('end'). Shouldn't everything I do in fetchResult() therefore happen after the http request has completed successfully?
fetchResult is the call, and the function inside that call is what happens once your data is retrieved. The variable in your module doesn't know this, so it tries to assign a value immediately, and fails. A callback is just another function call to allow that processed data to be used.
Ah ok, that does make sense. I didn't think far enough to see that there's still something else happening. However I'm not sure if I'm completely oblivious to something obvious or if it's just getting too late, but even though I now pass the callback function, this does exactly the same as it already did before. Is the only way to completely assign whatever 'data' is to a results variable by doing something like this? var results = ''; myModule(otherparams,function(data){results = data;});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.