Skip to content

Instantly share code, notes, and snippets.

@Axighi
Created August 26, 2016 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Axighi/420a1c637b3a664a0ddcbc26fd77a60a to your computer and use it in GitHub Desktop.
Save Axighi/420a1c637b3a664a0ddcbc26fd77a60a to your computer and use it in GitHub Desktop.
let fs = require("fs");
function run(taskDef) {
// create the iterator
let task = taskDef();
// start the task
let result = task.next();
// recursive function to iterate through
(function step() {
// if there's more to do
if (!result.done) {
// resolve to a promise to make it easy
let promise = Promise.resolve(result.value);
promise.then(function(value) {
result = task.next(value);
step();
}).catch(function(error) {
result = task.throw(error);
step();
});
}
}());
}
// Define a function to use with the task runner
function readFile(filename) {
return new Promise(function(resolve, reject) {
fs.readFile(filename, function(err, contents) {
if (err) {
reject(err);
} else {
resolve(contents);
}
});
});
}
// Run a task
run(function*() {
let contents = yield readFile("config.json");
doSomethingWith(contents);
console.log("Done");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment