1

I am writing a web crawler for reddit which only allows 1 request every 2 seconds and would like to use recursion to make the requests. After the series of get requests for 1 persons comments are complete, I would like to emit to show completion and call the comments again on the next username in a message queue. The problem is whenever I am more than one level deep I get a "TypeError: Object # has no method 'emit'".

I am also open for better ways to do this, I have just started learning node and am sure there are much better ways to accomplish this.

I have posted my code in the gist below...any help would be awesome!

https://gist.github.com/1729182

Hortinstein
  • 2,667
  • 1
  • 22
  • 22
  • Consider creating a minimal failing case and posting that here. Anyway, those errors are simple: you are doing `self.emit`, where `self` does not evaluate to an object with a property `emit` (much less one that evaluates to a function)... so what *exactly* is `self`, and why does/would what it evaluates to change? (These are questions for you, the developer/debugger ;-) –  Feb 03 '12 at 09:14
  • @pst why does it work when there is no recursive calls? I am still trying to wrap my head around javascript scoping...I think my problem lies there – Hortinstein Feb 03 '12 at 09:20
  • Consider posting code here, and reducing the code snippet to the minimum code that produces the error. – millimoose Feb 04 '12 at 00:32

1 Answers1

2

The issue is with this which is a keyword (not free variable) that evaluates to the "receiver" for the function call.

For instance, given:

x = {fn: function () {return this} }
x.fn()

Then inside fn, this evaluates to what x evaluated to (and thus x.fn() === x). In the code grabComments is being invoked with no receiver, in which case this reverts to the global object. You may be interested in Function.call/apply, or just simplify the code to handle recursion with a nested function so that self can remain bound-to in scope.

(In JavaScript, methods are not bound to objects: they are merely functions shoved into properties, so the receiver is paramount in determining this for the executiong function.)

See also:

Happy coding.

Community
  • 1
  • 1
  • Awesome! I am still not convinced that my solution is the best way and I will eventually go back and refactor once I better understand JavaScript, but apply worked for me. Those links are excellent as well! I used: ' grabComments.apply(self,args); ' . – Hortinstein Feb 04 '12 at 01:52
  • i would also like to know how I could nest recursion within the grabComments function, and still count on 'next' only being emmitted after the final invocation. Since node is non blocking...I really need to read those control flow articles, but for some reason the lan I am on is blocking how to node. Thanks for your help! – Hortinstein Feb 04 '12 at 01:58