3 ms·
I work in JS all the time, but was still a little skeptical of Node until I finally grasped the concept of Promises (the Bluebird library being my preference).
by untog 12y ago
I work in JS all the time, but was still a little skeptical of Node until I finally grasped the concept of Promises (the Bluebird library being my preference). It took the callback-driven, event loop system from a liability to a huge bonus - running operations in parallel is so simple now, and error handling is a breeze. Can't recommend it enough.
Now I'm spending my time writing view code that can run on both the server and client, allowing me to render the same stuff statically (for fast initial load and SEO) and dynamically on the client (for fast page changes).
- sillysaurus3 12y agoDo you happen to have any example code? I've had some bad experiences with "callback hell," so it's interesting to see that there are ways to prevent it from becoming a problem.
- jowiar 12y agoFor me, callback hell is a code smell - it means that I'm thinking imperatively and not, umm, eventedly. The general fix is to call something a component - give it a name and such, and have it fire some events that something else should listen to.
- untog 12y agoOne of my favourite parts of Bluebird is the 'Promisify' function. It allows you to take existing Node modules and use them as promises. Here's an example of interating over an array of files, only writing ones that don't already exist: http://pastie.org/9559209 http://pastie.org/9559209 It's also one of the reasons that I've ended up liking CoffeeScript more - Promises have a lot of function() and return statements, CS makes that kind of code a lot cleaner. For instance, that JS could be this short in CS: Promise.filter files, (file) -> fs.existsAsync(file).then (doesExist) -> !doesExist .each (file) -> fs.writeFileAsync(file.filename,file.content) .then -> Promise.map files, (file) -> fs.readFileAsync(file,'UTF-8') .then (fileContents) -> console.log(fileContents); ### Will return: [ "File 1 Content", "File 4 Content", "File 3 Content" ] ### .catch (err) -> # This will catch any and all errors that happened above.
- ufo 12y agoThe event loop argument is the least convincing one for me. Any other language with green-threads/coroutines/continuations/etc lets you write an event-loop system without needing to uglify your code with callbacks or promises. Javascript is finally catching on to this with generators (yield statement) but it bugs me when people talk about callbacks as if they were a good thing.