Created
December 18, 2011 12:09
-
-
Save bjouhier/1493206 to your computer and use it in GitHub Desktop.
Callback wrapper that implements trampoline with try/catch
This file contains hidden or 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
| // 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); | |
| }) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gotcha: if you have
try/catchin your code, you must rethrow the special trampoline exception in yourcatchclauses. You can do it withif (Array.isArray(ex)) throw ex;.