Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to understand how to design node.js applications, but it seems there is something I can't grasp about asynchronous programming.

Let's say my application needs to access a database. In a synchronous environment I would implement a data access class with a read() method, returning an associative array.

In node.js, because code is executed asynchronously, this method can't return a value, so, after execution, it will have to "do" something as a side effect. It will then contain some code which does something else than just reading data.

Let's suppose I want to call this method multiple times, each time with a different success callback. Since the callback is included in the method itself, I can't find a clean way to do this without either duplicating the method or specifying all possible callbacks in a long switch statement.

What is the proper way to handle this problem? Am I approaching it the wrong way?

share|improve this question
It is not very clear what is your problem, maybe rephrase it. I'd have two comments: 1. Maybe you just need to get used to async/callback way of doing things, I do not see anything like "unmanageable code soup" there. 2. Ad "loosely coupled classes": do you really need "classes" there? Classes are not needed to do OO neither to do good design. Maybe change the title. – herby Sep 4 '12 at 18:18
I'm not certain what this code soup is either? – Jimmy Hoffa Sep 4 '12 at 20:58
I changed the title and rephrased the question. I hope it is clearer now. – lortabac Sep 5 '12 at 6:37
up vote 11 down vote accepted

Since you can pass functions as parameters, it is common to pass a "callback" function to these sorts of functions. So, for example, you may have a "read" function that looks like this:

function getUser(userId, callback) {
  var mydbAPI = something;
  var myQuery = somethingElse;

  mydbAPI.getUser(myQuery, function(data) {
    //parse data a little here:
    myParsedData = ...;


You can then call the read method like this:

getUser(userId, function(parsedData) {
  // something with parsedData
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.