Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Dec 18, 2011

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
You can’t perform that action at this time.