Created
August 24, 2014 13:14
-
-
Save markmarijnissen/19864cc307f35e793bf3 to your computer and use it in GitHub Desktop.
Convert Cordova-style callbacks to Nodejs-style callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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