Saturday, March 5, 2011

A consistent naming scheme proposal for Javascript callbacks

Basically, there are two schemes of javascript callbacks:


function(other_params, onSuccess, onError){
}


and

function(other_params, callback){
}


where callback is called with:

callback(null, params..)

on success, and


callback(exceptionobject)

on failure.

What if we would choose the first one, but instead call them differently?

function(other_params, _return, _throw){
}


Imagine the body:

function(other_params, _return, _throw){
var params;/*...*/
some_other_async_operation(params, function(result){
return_(result);
}, function _catch(e){
throw_(e);
}
}

Is it more clean what's happening here?

I came to a level, with some helper functions:

(function(x){
var return_ = arguments.callee.getCallback(arguments);var throw_ = arguments.callee.getErrorCallback(arguments);
var result = {};
try_(result, "=", db.view.call_(db, "xxx/xxx", {startkey:x+"_", endkey:x+"_z", group:true }))(function(){
console.log("success");
console.log(result.length);
}).catch_(function(exception){
console.log("error");
console.log(exception);
throw_(exception);
}).finally_(function(){
console.log("returning");
return_();
})();
})(10);

Opinions, ideas?

No comments:

Post a Comment