Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active August 29, 2015 14:21
Show Gist options
  • Save ernestlv/a822d9adc4fcca2d8f9f to your computer and use it in GitHub Desktop.
Save ernestlv/a822d9adc4fcca2d8f9f to your computer and use it in GitHub Desktop.
Consume an ajax request in Node.js without blocking the browser request
var cache = require("./cache-service");
var http = require("./http-monitor");
var NOT_READY = { statusCode:202, data:"" };
function doRequest(serviceID, httpReq, serviceResults){
var httpRes = { //overrides httpRes.json() dispatches data without blocking the browser
json:function(statusCode, data){
if (arguments.length === 1){
data = statusCode;
statusCode = 200;
}
if (!httpReq.completed) {
serviceResults[serviceID] = { //if data is available save it
statusCode: statusCode,
data: data
}
}
}
};
if (!cache[serviceID](httpReq, httpRes)){ //check cache, if data is not available, request service
http[serviceID](httpReq, httpRes);
}
}
exports = module.exports = {
test: function(httpReq, httpRes){ //this call is going to ask for two web services
var serviceResults = {
"getClients": NOT_READY, //by default we assume service data won't be available
"getSales": NOT_READY
};
httpReq.completed = false;
//List of service requests
doRequest("getClients", httpReq, serviceResults); //request service data
doRequest("getSales", httpReq, serviceResults);
httpRes.json(serviceResults); //dispatch results to browser immediately
httpReq.completed = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment