Skip to content

Instantly share code, notes, and snippets.

@markmarijnissen
Created August 24, 2014 13:14
Show Gist options
  • Save markmarijnissen/19864cc307f35e793bf3 to your computer and use it in GitHub Desktop.
Save markmarijnissen/19864cc307f35e793bf3 to your computer and use it in GitHub Desktop.
Convert Cordova-style callbacks to Nodejs-style callbacks
/**
* Copy-paste this in your console to test if function works as expected
**/
function toNodejsFn(cordovaFn,self){
return function(){
var args = Array.prototype.slice.call(arguments,0);
var callback = args.splice(args.length-1,1)[0];
args.push(function onSuccess(){
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(null);
callback.apply(self,args);
});
args.push(function onError(){
var args = Array.prototype.slice.call(arguments, 0);
// ensure the first argument is not-null
if(args.length === 0 || !args[0]) args.unshift(true);
callback.apply(self,args);
});
cordovaFn.apply(cordovaFn,args);
};
}
function isSmaller(a,b,success,error){
if(a < b){
success(b-a);
} else {
error();
}
}
var isSmallerTest = toNodejsFn(isSmaller);
isSmallerTest(1,3,function(err,res){
console.log('isSmaller(1,3): err === null',err === null);
console.log('isSmaller(1,3): res === 2 (difference)',res === 2);
});
isSmallerTest(4,1,function(err,res){
console.log('isSmaller(4,1): err !== null',err !== null);
});
/**
* convert a cordova-style function: fn(a,b,c,onSuccess,onError)
* to a nodejs-style function: fn(a,b,c,callback)
*
* where callback is fn(err,response) and err should be falsy (null,false,0,'') for success responses
*
**/
module.exports = function toNodejsFn(cordovaFn,self){
return function(){
var args = Array.prototype.slice.call(arguments,0);
var callback = args.splice(args.length-1,1)[0];
args.push(function onSuccess(){
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(null);
callback.apply(self,args);
});
args.push(function onError(){
var args = Array.prototype.slice.call(arguments, 0);
// ensure the first argument is not-null
if(args.length === 0 || !args[0]) args.unshift(true);
callback.apply(self,args);
});
cordovaFn.apply(cordovaFn,args);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment