I'm using an anonymous function to perform some work on the html I get back using Restler's get function:
var some_function() {
var outer_var;
rest.get(url).on('complete', function(result, response) {
if (result instanceof Error) {
sys.puts('Error: ' + result.message);
} else {
var inner_var;
// do stuff on **result** to build **inner_var**
outer_var = inner_var;
}
});
return outer_var;
}
How can I get the value of inner_var out to the some_function scope and return it? What I have written here doesn't work.
The get call is asynchronous, it will take some time and call your callback later. However, after calling get, your script keeps executing and goes to the next instruction. So here is what happens:
You can't have your some_function return a value for something that is asynchronous, so you will have to use a callback instead and let your code call it once data is processed.
var some_function(callback) {
rest.get(url).on('complete', function(result, response) {
if (result instanceof Error) {
sys.puts('Error: ' + result.message);
} else {
var inner_var;
// do stuff on **result** to build **inner_var**
callback(inner_var);
}
});
}
Like most of the modules of node, Restler is also a event based library having async calls. So at the time you do return outer_var; the complete callback was not necessarily called (With some libraries it could be if it the result was cached, but you should always expect that it is called asynchronous).
You can see this behavior if you add some logging:
var some_function() {
var outer_var;
console.log("before registration of callback"); //<----------
rest.get(url).on('complete', function(result, response) {
console.log("callback is called"); //<----------
if (result instanceof Error) {
sys.puts('Error: ' + result.message);
} else {
var inner_var;
// do stuff on **result** to build **inner_var**
outer_var = inner_var;
}
});
console.log("after registration of callback"); //<----------
return outer_var;
}
So if you would like to do something with this value you would need to call the function that should do something with this value out of your complete callback.
var outer_var; from your function some_function;var outer_var; upper then your functionIt should be work after you did step 1, not really need step 2.