cfy - CallbackiFY
Simplifies interop between co (promise / generator-based) async functions, and async callback-based functions (both node-style nodebacks where the first parameter is an error, and regular callbacks).
Features
- Write callback-based async functions using generators (using
cfy
). Can also write node-style ("nodeback") async functions (usingcfy_node
). If the resulting function is not passed a callback, an ES6 Promise is returned. - Can
yield
callback-based functions in generators (usingyfy
), as well as node-style nodeback-based functions (usingyfy_node
). - All features of generators wrapped with co (such as yielding Promises) can be used generators wrapped with
cfy
andcfy_node
.
Install
npm install cfy
Usage
For the purpose of these examples, we assume you have required the library as follows:
var cfy cfy_node ycall ycall_node yfy yfy_node = ;
Examples
Turning a generator into a callback/promise-based async function
var cfy = ; var cfy_example = ; ; // 5; // 5
Using callback-based async functions in generators
var cfy yfy = ; var yfy_example_with_arguments = ; ; // 15; // 15
Writing a wrapper for setTimeout (sleep)
var sleep = ; var sleep_example = ; ; // 7
API
cfy
cfy
creates a callback-style function from a generator
var cfy_example = ; ; // 5
If the last argument is not a function, a promise will be returned instead:
; // 5
cfy_node
cfy_node
creates a nodeback-style function from a generator
var cfy_node_example = ; ; // 5
If the last argument is not a function, a promise will be returned instead:
;
yfy
yfy
transforms a callback-style function into a promise which can be yielded within a generator.
{ ;} var yfy_example_with_arguments = ; ; // 15
yfy_node
yfy_node
transforms a nodeback-style function into a promise which can be yielded within a generator.
{ ;} var yfy_node_example_with_arguments = ; ; // 15
ycall
ycall
is a shorthand that calls yfy
on a callback-based function and calls it with the remaining parameters. So ycall(func, x, y)
is equivalent to yfy(func)(x, y)
{ ;} var ycall_example_with_arguments = ; ; // 15
ycall_node
ycall_node
is a shorthand that calls yfy_node
on a nodeback-based function and calls it with the remaining parameters. So ycall_node(func, x, y)
is equivalent to yfy_node(func)(x, y)
{ ;} var ycall_node_example_with_arguments = ; ; // 15
More Examples
You will find more examples in example.js
(for interop with normal callback-based async functions) and example_node.js
(for interop with node-style nodeback-based async functions). The unit tests include examples of usage from Livescript.
Credits
By Geza Kovacs