Skip to content

Instantly share code, notes, and snippets.

@johnbeech
Created July 3, 2015 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnbeech/b976e30e3c14c53a5571 to your computer and use it in GitHub Desktop.
Save johnbeech/b976e30e3c14c53a5571 to your computer and use it in GitHub Desktop.
Harness for comparing and contrasting Class Based API or Callback Function API
// Config Service using callback
var Service = function(query, readyCallback, errorCallback) {
var arc = "arc data";
if(query.indexOf("bad") > -1) {
if(typeof errorCallback === 'function') {
errorCallback("bad contents");
}
}
else {
if(typeof readyCallback === 'function') {
readyCallback(arc);
}
}
}
module.exports = Service;
// Config Service API using promises?
var Service = function() {
this.ready = function(callback) { this.readyCallback = callback; return this; };
this.error = function(callback) { this.errorCallback = callback; return this; };
this.config = function(query) { handleQuery(query); };
function handleQuery(query) {
var arc = "arc data";
if(query.indexOf("bad") > -1) {
if(typeof this.errorCallback === 'function') {
this.errorCallback("bad contents");
}
}
else {
if(typeof this.readyCallback === 'function') {
this.readyCallback(arc);
}
}
}
return this;
}
module.exports = Service;
// Example A: Service as a factory that can be configured
var serviceFactory = require('./configService-class');
var serviceA = serviceFactory().ready(function(result) {
console.log("A Result: " + result);
}).error(function(error) {
console.log("A Error: " + error);
});
serviceA.config("A1 my good query");
serviceA.config("A2 my nice query");
serviceA.config("A3 my bad query");
// Example B: Service as a function with a callback
var serviceB = require('./configService-callbacks');
function handleSucess(result) {
console.log("B Result: " + result);
}
function handleError(error) {
console.log("B Error: " + error);
}
serviceB("B1 my good query", handleSucess, handleError);
serviceB("B2 my nice query", handleSucess, handleError);
serviceB("B3 my bad query", handleSucess, handleError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment