Skip to content

Instantly share code, notes, and snippets.

@bjouhier
Created December 18, 2011 12:09
Show Gist options
  • Save bjouhier/1493206 to your computer and use it in GitHub Desktop.
Save bjouhier/1493206 to your computer and use it in GitHub Desktop.
Callback wrapper that implements trampoline with try/catch
// callback wrapper for trampoline
var depth = 0;
var maxDepth = 100;
var marker = {};
function trampo(cb) {
return function(e, r) {
var d = depth++;
try {
if (depth === maxDepth)
throw [marker, cb, e, r];
else
cb(e, r);
depth = d;
} catch (ex) {
depth = d;
if (ex[0] === marker && depth == 0)
ex[1](ex[2], ex[3]);
else
throw ex;
}
}
}
// test program
function fibo(async, i, cb) {
cb = async ? delay(cb) : trampo(cb);
if (i <= 1) cb(null, 1);
else fibo(async, i - 1, function(e, r1) {
if (e) return cb(e);
fibo(async, i - 2, function(e, r2) {
if (e) return cb(e);
cb(null, r1 + r2);
});
});
}
function delay(cb) {
return function(e, r) {
process.nextTick(function() {
cb(e, r)
});
}
}
fibo(false, 20, function(e, r) {
if (e) throw e;
console.log(r);
})
@bjouhier
Copy link
Author

Gotcha: if you have try/catch in your code, you must rethrow the special trampoline exception in your catch clauses. You can do it with if (Array.isArray(ex)) throw ex;.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment