Last active
February 28, 2016 17:48
-
-
Save nnarhinen/6256128 to your computer and use it in GitHub Desktop.
Example files on how to use ES6 generators in your code to reduce callback nesting
This file contains 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
'use strict'; | |
/* | |
* Express server using ES6 generators | |
* Use node 0.11 | |
* run with node --harmony express-server-generator.js | |
*/ | |
var Q = require('q'), | |
HTTP = require('q-io/http'), | |
express = require('express'), | |
http = require('http'); | |
var app = express(); | |
app.set('port', process.env.PORT || 3001); | |
app.use(express.favicon()); | |
app.use(express.logger('dev')); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(express.cookieParser()); | |
app.use(app.router); | |
// development only | |
if ('development' == app.get('env')) { | |
app.use(express.errorHandler()); | |
} | |
app.get('/foo', Q.async(function* (req, res) { | |
// I know this could be piped with 'traditional' means also, but in a real world case you would do async database etc calls here | |
var resp = yield HTTP.read(path); | |
res.send(resp.toString()); | |
})); | |
http.createServer(app).listen(app.get('port'), function() { | |
console.log('Express server listening on port ' + app.get('port')); | |
}); |
This file contains 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
'use strict'; | |
/* | |
* HTTP request using ES6 generators | |
* Use node 0.11 | |
* run with node --harmony request-generator.js | |
*/ | |
var Q = require('q'), | |
HTTP = require('q-io/http'); | |
var request = Q.async(function* (path) { | |
var response = yield HTTP.read(path); | |
return response; | |
}); | |
request('http://www.example.com').then(function(resp) { | |
console.log(resp.toString()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment