Skip to content Skip to sidebar Skip to footer

Unable To Call Functions With Require.js

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. T

Solution 1:

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);
});

Solution 2:

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.

Post a Comment for "Unable To Call Functions With Require.js"