Skip to content

Instantly share code, notes, and snippets.

@VivienAdnot
Created October 7, 2016 12:14
Show Gist options
  • Save VivienAdnot/0fdf6c12bbe878e26da4d898bc2c1d3d to your computer and use it in GitHub Desktop.
Save VivienAdnot/0fdf6c12bbe878e26da4d898bc2c1d3d to your computer and use it in GitHub Desktop.
how to transform a sync function that returns a value or throws an exception, as async that fires a callback
function asyncify(f) {
return function _asyncify() {
var args = Array.prototype.slice.call(arguments, 0);
var argsWithoutLast = args.slice(0, -1);
var callback = args[args.length - 1];
var result, error;
try {
result = f.apply(this, argsWithoutLast);
} catch (e) {
error = e;
}
setTimeout(function() {
callback(error, result);
}, 0);
}
}
// example
function head(xs) {
if (_.isArray(xs) && !_.isEmpty(xs)) {
return xs[0];
} else {
throw "Can't get head of empty array.";
}
}
var cbHead = asyncify(head);
cbHead([1, 2, 3], function(err, result) {
// result === 1
});
cbHead([], function(err, result) {
// err === "Can't get head of empty array.";
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment