Created
October 3, 2014 15:54
-
-
Save jackfranklin/d68da70ed43203c2eb4a to your computer and use it in GitHub Desktop.
playing with generators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Q = require('Q'); | |
var fs = require('fs'); | |
var generator = Q.async(function* () { | |
yield 10 | |
console.log('yielded 10'); | |
yield 20 | |
console.log('yielded 20'); | |
yield 30 | |
console.log('yielded 30'); | |
return 40; | |
}); | |
generator().then(function(last) { | |
console.log(last); | |
}); | |
function readFile(filename, enc){ | |
return new Promise(function (fulfill, reject){ | |
fs.readFile(filename, enc, function (err, res){ | |
if (err) reject(err) | |
else fulfill(res) | |
}) | |
}) | |
} | |
var readJSON = Q.async(function* (filename) { | |
return JSON.parse(yield readFile(filename, 'utf8')); | |
}); | |
Q.spawn(function* () { | |
var content = yield readJSON('foo.json', 'utf8'); | |
console.log(content); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment