Node.js Callback Issues

Problem

Been working on a Node.js restful web service that is hosted on OpenShift. Currently I have had success with simple method calls and such, but can not seem to get the http response to work through an asynchronous callback.

Here is what I currently have:

var http = require("http");
var url = require("url"); // used to get the requested method name as well as parameters
var util = require("util");

// global variables


// router function
function route(pathname, query, callbackFunc) {
  //return executeMethod(pathname, query);
  var returnValue;

  switch (pathname.toUpperCase()) {
    case "/ADD":
        returnValue = add(query['num1'], query['num2']);
        //util.process.nextTick(function() {
        //callbackFunc(null, returnValue);
        //});
        break;
    case "/ADDASYNC":
        //addAsync(query['num1'], query['num2'], callback);
        break;   
    default:
        returnValue = "method not found";
        break;
  }

  //return returnValue;
  //return "Route for request " + pathname + " complete, query: " + query;
}


// actual web method execution
function add(num1, num2){
    //return "add method called with values: " + num1 + " " + num2;
    return parseFloat(num1) + parseFloat(num2);
}

function addAsync(num1, num2, callback){
    //util.process.nextTick(function(){
    //    var value = parseFloat(num1) + parseFloat(num2);
    //    util.process.nextTick(function(){
    //        callback(value);
    //    });
    //});
}

// main request handler for server
function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    var query = url.parse(request.url, true).query;
    console.log("Request for " + pathname + " Recieved");

    response.setTimeout(500);

    var myCallback = function(err, data){
        if(err){
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write('an error occured with requested method');
            response.end();
        }else{
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write(data);
            response.end();
        }

    }

    //var finalValue = route(pathname, query);
    //var finalValue = 0;
    (function(){route(pathname, query, myCallback)})();
    response.writeContinue();
    //process.nextTick(myCallback(null, 'hello world'));
    setTimeout(function(){
        myCallback(null, "hello world");
    }, 15);

    //myCallback();
    //response.writeHead(200, {"Content-Type": "text/plain"});
    //response.write("Hello World. You requested: " + pathname + " with type " + pathname.type +  ", value: " + finalValue);
    //response.end();
}

// create the server and signal console of start
http.createServer(onRequest).listen(8080, process.env.OPENSHIFT_INTERNAL_IP);
// for debug
//http.createServer(onRequest).listen(process.env.PORT, process.env.IP);
console.log("Server has started. Listening to port: " + 8080 + " ip address: " + process.env.OPENSHIFT_INTERNAL_IP);

If I call the myCallback method directly inside the onRequest method, then I get a response back without any issues; however, calling the myCallback function inside the onRequest or route methods using process.nextTick or setTimeout does not seem to be working. I am working on this project using the Cloud9 IDE with direct git push to OpenShift so I am having some difficulties with my debug but have tried quite a few different approaches with no success, including setting the request.setTimeout function to provide some time for the timer/process event to fire. My current OpenShift app is running Node.js 0.6. Is there anything Obvious that could be causing issues that I might be missing?

Problem courtesy of: StMotorSpark

Solution

I got your setTimeout to work by doing this:

  • comment out "response.setTimeout(500);" on line 54. It's invalid.
  • comment out "(function(){route(pathname, query, myCallback)})();" on line 71. Also invalid.
  • change timeout time to 5000 on line 76 (5000ms = 5 seconds)

For nextTick to work:

  • everywhere only do "process.nextTick" not "util.process.nextTick".
  • change line 16 to: "returnValue = add(query['num1'], query['num2']).toString();" (have to cast it as a string!)
  • uncomment 17, 18, 19 to see this will now work
  • comment out line 54, you don't need this
  • change line 70 to "route(pathname, query, myCallback);"

You should see what you did wrong now.

Solution courtesy of: CommaToast

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.