Reputation: 1
I am new to Javascript, I am confused about the code below for hours. I wanna know why i can't assign the value of result to htmlContent. Thanks!
var htmlContent = fs.readFileSync(program.file);
restler.get('http://google.com').on('complete', function(result) {
if (result instanceof Error) {
util.puts('Error: ' + result.message);
} else {
htmlContent = result;
}
});
console.log(htmlContent);
Upvotes: 0
Views: 101
Reputation: 955
Here, your function inside the .on()
will be called asynchronously (in simple words it will get executed when "complete" event occurs i.e. some later time) and you are using console.log(htmlContent)
is regular function call, so you can not set htmlContent
value inside the function this way.
If you want to use result
value in any other function then you should pass this value to your next function. I hope this will work.
Upvotes: 0
Reputation: 1
I would look up the concept of futures and promises in JS, this might help clear up some fundamentals: http://monochrome.sutic.nu/2012/04/06/javascript-futures.html
When you are using continuations in JS (a requirement in node.js especially), you really need to get your head around them.
Upvotes: 0
Reputation: 73
The problem here is that the line starting with restler.get
begins before the console.log
, but it doesn't finish before it necessarily.
You should put your console.log
inside the restler.get
call.
Upvotes: 2