Use fibers with functions that take callbacks.
A tiny library for node that helps you use fibers with node-style callbacks and works similarly to suspend
Spawn a fiber task. From within your task, call your async functions with yield and pass them a resume function instead of a callback:
Handle errors with
catch, or as return results via
fibbyrun// Throwing resumetry fibyieldfsreadFile"test.js" fibresume;catch e /* handle the error */// Non-throwing resume always results with an arrayvar err_res = fibyieldfsreadFile"test.js" fibresumenothrow;if err_res0 /* handle error */;
Dont like nested parens? Want to keep things brief? Use
resume.nt instead of
Want to catch all uncaught exceptions? You can pass a callback argument to
fibbyrunvar data = fibyieldfsreadFile"test.js" fibresumet;// thrown error propagates here automagically// because it was not caught.;
You can also use
fibby instead to create a function which
can accept multiple arguments and a callback. The arguments will be
passed to your fiber right after the first
var getLine = fibbyfnvar data = fibyieldfsreadFilefile fibresumet;return datatoStringsplit'\n'number;;getLine'test.js' 2// thrown error propagates here automagically// because it was not caught.// If the file actually exists, lineContent// will contain the second line;
note: make sure that you pass the callback last.
Notice how if you return a value at the end of your fiber, it will be passed as a result to the callback. If you return undefined, the callback will not be called.
Your async functions call the callback with more than 2 arguments? Not a problem - the yield call from within your task will return an array instead.
callbacknull 'arg1' 'arg2';fibbyrunvar res = fibyieldreturnsmorefibresumet;var arg1 = res0;var arg2 = res1;var nothrowres = fibyieldreturnsmorefibresument;var err = res0;var arg1 = res1;var arg2 = res2;;
test/index.js for more examples and tests.