How to write reusable code in node.js
- by lortabac
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?