Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Best practice for code after callback

Best practice for code after callback


Here's what I'm trying to do.

I'm currently using node.js and one of the things it allows you to do is:

socket.on("sometopic", function() { 
    // this is a callback

Now let's say I have 10 different topics, each of these with one corresponding handling Function that I keep in my "window", as such:

windows.callbacks["topic_a"] = function() {
    // code for cb a

windows.callbacks["topic_b"] = function() {
    // code for cb b

windows.callbacks["topic_z"] = function() {
    // code for cb z

And there's a piece of Code I would like to have executed at the end of every callback. An easy way out is to create a function with this code and add a call at the end of each callback but this is far from being elegant.

Can anyone suggest a better solution for this? Is there a best practice that I'm unaware of? I'm fairly green to this kind of functional programming.

Problem courtesy of: Tiago Espinha



// helper

function teardownWith(fn){
  return function (cb){
    return function(){
      return (cb(), fn());

// prepare a modified function

var endWithDate = teardownWith(function(){

// pass our callback into the modified function
// endWithDate() returns the final callback.

window.callbacks["cb_a"] = endWithDate(function(){
   // code for cb_a
Solution courtesy of: user943702


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Best practice for code after callback


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription