0

i try to write an module for my node.js server with require.js that just returns the object i want to get from an url. But somehow i can't return the values i get with my method. The http.get... is performed after i return the value, so that i just get "undefined" but why?

Could you please help me? Sorry if that is an stupid questen but im really new to javascript node.js and require.js.

define(['http'], function(http){
    console.log('Hi ich bin pullArchiveVolume');

    var response = 1;
    console.log('Log 1: ' + response);

    http.get("http:...", function(res) {
        var body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {

            console.log("Log 2: " + response);
            response = 2;
            console.log("Log 3: " + response);

            response = JSON.parse(body);
            return response;
            // console.log("Log 2 :", response);
            // console.log("Got response: ", response);
        });
    }).on('error', function(e) {
      console.log("Got error: " + e.message);
    });

    console.log("Log 4: " + response);
    return response;

})

Console Output:

Hi ich bin pullArchiveVolume
Log 1: 1
log 4: 1
log 2: 1
log 3: 2

Thanks!

2 Answers2

2

You can't have a function that makes an async call just return something (unless it's a promise).

You need to have your function take a callback parameter:

function foo(callback) {
  doSomethingAsync(function(data) {
    // fire callback, which is a function that takes an argument 'data'
    callback(data)
  });
}

Then you can use it like this:

foo(function(data) {
  doStuffWith(data);
});
Community
  • 1
  • 1
lxe
  • 7,051
  • 2
  • 20
  • 32
  • Thanks it works, but how can i return the object and call this in another module? – user2942012 Nov 05 '13 at 10:30
  • You will just need to return a function that takes a callback instead of an object that holds a result. Instead of doing `return response` you'll have to wrap your logic in a function, like I showed, and return that function instead: `return foo`. – lxe Nov 05 '13 at 20:35
0

The reason why you get what you get is that http.get(...) only initiates a network operation. At some indefinite point in the future the callbacks you gave to it will be executed. However, http.get(...) returns right away, before its callbacks are run. (Hence, it is an asynchronous operation). So by the time you hit your return statement the network operation is not complete yet and you return the initial value you gave to your response variable. Eventually, the network operation completes, your success callback is called and then you update response to the value you really wanted.

As others have said, you need to use callbacks or promises. Or rethink your design.

Louis
  • 146,715
  • 28
  • 274
  • 320