Re:What it's like building a real website in Node.js
by mjs on Monday February 28, 2011 @08:23AM
(#2271100)
If you have a function foo() that takes a callback as an argument i.e. something like:
foo(..., function (n) {
// closure over q, r, s
});
Then what you can do is create a separate function, bar() that takes q, r, s as an argument, and returns a function: function bar(q, r, s) {
return function(n) {
// still has dependency on q, r, s
}
}
Once you have bar(), the foo() call above can be written as: foo(..., bar(q, r, s));
and you save one level of nesting. (This also makes the dependencies explicit, which is helpful.)The main loop of
https://github.com/ithinkihaveacat/node-fishback/blob/ce5f9c...
does quite a lot of this, if you want a real example.
Re:What it's like building a real website in Node.js
by jlyke on Monday February 28, 2011 @10:53AM
(#2271590)
This technique reminds me of Lambda Lifting: http://en.wikipedia.org/wiki/Lambda_lifting
Re:What it's like building a real website in Node.js
by svetlyak40wt on Monday February 28, 2011 @12:28PM
(#2271970)
Why not to write it in a much simplier way? Like this:
function bar(n) {
// still has dependency on q, r, s
}
foo(..., bar);
Re:What it's like building a real website in Node.js
by mjs on Monday February 28, 2011 @01:01PM
(#2272097)
Yeah, that's nicer if bar() can be defined at the same "level" as foo() but if it makes more sense to move it somewhere else the closed-over variables need to be passed.
Re:What it's like building a real website in Node.js
by htsh on Monday February 28, 2011 @10:50AM
(#2271579)
We've been using the flow control helpers in async.js to help us with the nesting issue: (https://github.com/caolan/async).
We use the waterfall most, as it allows one to run an array of function in a series with a callback at the end of the series.
Can you share a few? Either here or as a blog post?