Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: What techniques are there for writing clean, simple callback code?

node.js code is known for turning into callback spaghetti.

What are the best techniques for overcoming this problem and writing clean, uncomplex, easy to understand callback code in node.js?

like image 686
Duke Dougal Avatar asked Mar 10 '11 20:03

Duke Dougal


People also ask

How do you write a clean code in node JS?

Modularize Your Functions An easy way to declutter your code is creating a function for every single task. If a function does more than its name implies, you should consider splitting the functionality and creating another function. Maintaining smaller functional chunks makes your code look neat.

How do you write a callback function in node?

For example, a function to read a file may start reading file and return the control to the execution environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as a parameter.

What's the most common first argument given to the node JS callback handler?

The first argument of the callback handler should be the error and the second argument can be the result of the operation. While calling the callback function if there is an error we can call it like callback(err) otherwise we can call it like callback(null, result).


1 Answers

Take a look at Promises: http://promises-aplus.github.io/promises-spec/

It is an open standard which intended to solve this issue.

I am using node module 'q', which implements this standard: https://github.com/kriskowal/q

Simple use case:

var Q = require('q'); 

For example we have method like:

var foo = function(id) {   var qdef = Q.defer();    Model.find(id).success(function(result) {     qdef.resolve(result);   });    return (qdef.promise); } 

Then we can chain promises by method .then():

foo(<any-id>) .then(function(result) {   // another promise }) .then(function() {   // so on }); 

It is also possible to creating promise from values like:

Q([]).then(function(val) { val.push('foo') }); 

And much more, see docs.

See also:

  • http://jeditoolkit.com/2012/04/26/code-logic-not-mechanics.html#post
  • http://wiki.commonjs.org/wiki/Promises/A
like image 199
x'ES Avatar answered Sep 19 '22 10:09

x'ES