Comparing version 0.1.2 to 0.1.3
28
main.js
@@ -11,2 +11,8 @@ 'use strict'; | ||
// Utils | ||
function isGenerator(fn) { | ||
return fn.constructor.name === 'GeneratorFunction' || typeof fn.next == 'function'; | ||
} | ||
/** | ||
@@ -62,4 +68,26 @@ * Runs a generator function as follows: function* (next, end) {...} | ||
/** | ||
* Preprocess callback functions passed as arguments, to support generators. | ||
* If a generator is passed instead of a callback, then a wrapper callback is | ||
* created. | ||
*/ | ||
gensy.callback = function (callback) { | ||
if (!isGenerator(callback)) { | ||
return callback; | ||
} | ||
var generator = callback; | ||
return function (error, data) { | ||
if (error) { | ||
return setImmediate(function () { | ||
generator.throw(error); | ||
}); | ||
} | ||
setImmediate(function () { | ||
return generator.next(data); | ||
}); | ||
}; | ||
}; | ||
/** | ||
* Export GENSY | ||
*/ | ||
module.exports = gensy; |
{ | ||
"name": "gensy", | ||
"version": "0.1.2", | ||
"version": "0.1.3", | ||
"description": "Asynchronous utils focused on generators", | ||
@@ -5,0 +5,0 @@ "keywords": ["asynchrony", "callback", "generator", "es6", "async"], |
@@ -70,2 +70,33 @@ # GENSY | ||
### Support both, callbacks and generators | ||
In order to use a simple function from a generator, it has to accept an argument where the `next` generator is passed. | ||
This is a problem if that functions are used elsewhere but receiving a callback instead of a generator, and we want to keep that compatibility. | ||
Gensy can be used then to preprocess the callback, so generators can be passed, too: | ||
```javascript | ||
function passMeCallbacksOrGenerators (thing) { | ||
callback = gensy.callback(thing); | ||
// ... Do some async work | ||
callback(error, result); | ||
} | ||
``` | ||
The previous code ensures that received `callback` can be both a function or a generator. The transformation allows us to use it as a simple callback, where the first argument is the error, and the second one is the returning data. It is important to keep this convention. If an error occurs and we call `callback(error)`, then our caller generator will fall in the `catch` statement, receiving it. | ||
So now, this function can be used passing both, generators or traditional callbacks: | ||
```javascript | ||
passMeCallbacksOrGenerators(function (error, result) { | ||
// I'm a traditional callback | ||
}); | ||
gensy(function* (next) { | ||
try { | ||
var x = yield passMeCallbacksOrGenerators(next); | ||
// I'm a generator, with yield statements | ||
} catch (error) {...} | ||
}); | ||
``` | ||
### Generator series | ||
@@ -72,0 +103,0 @@ |
8204
127
132