Commit 5a1c9988 authored by David Votrubec's avatar David Votrubec

Added thunkify function

parent 5ffd96e4
......@@ -4,11 +4,13 @@
* The runner function repeatedly calls the supplied generator function
* until all yields are exhausted.
*
* The function passed to run() can be a thunked function. See thunkify.js
*
* IT DOES NOT WORK WITH PROMISES
* because if continuable.value is a promise object, it can not be called as function
* because when continuable.value is a promise object, it can not be called as a function
*/
module.exports = function run(/*iterator fn*/ genFn) {
var iterator = genFn(); // [1]
module.exports = function run(/*iterator fn*/ generatorFn) {
var iterator = generatorFn(); // [1]
next(); // [2]
function next (err, value) { // [3]
......
"use strict";
const run = require('./03-run-function');
const thunkify = require('./thunkify');
const fs = require('fs');
const readFile = thunkify(fs.readFile);
run(function* () {
try {
const fileContent = yield readFile('./es6/blabla.json')
console.log(fileContent);
}
catch (er) {
console.error(er);
}
})
\ No newline at end of file
"use strict";
var run = require('./03-run-function');
var spawn = require('./04-spawn-function');
spawn(function*(){
......
{
"colorsArray":[{
"red":"#f00",
"green":"#0f0",
"blue":"#00f",
"cyan":"#0ff",
"magenta":"#f0f",
"yellow":"#ff0",
"black":"#000"
}
]
}
\ No newline at end of file
"use strict";
/**
* Thunkify take single function as its argument [1]
* and returns a parameters-less function [2]
* which when called returns another function [3]
* The thunked function is very useful when used with generators and the run function (see 03-run-function.js)
*
* --------------------------------------------------------------------
* Example usage
* var fs = require('fs')
* var readFile = thunkify(fs.readFile) // [1]
* var readAsyncJs = readFile('./myFile.js') // [2]
* readMyFileJs(function (err, fileData) { ... }) // [3]
* --------------------------------------------------------------------
*
* inspired by https://strongloop.com/strongblog/how-to-generators-node-js-yield-use-cases/
*/
module.exports = function thunkify (nodefn) { // [1]
return function () { // [2]
var args = Array.prototype.slice.call(arguments);
return function (cb) { // [3]
args.push(cb); // add cb to the argument array
nodefn.apply(this, args);
}
}
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment