Skip to content

Instantly share code, notes, and snippets.

@jdriscoll

jdriscoll/app.js Secret

Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdriscoll/af914bd6085c5af68032 to your computer and use it in GitHub Desktop.
Save jdriscoll/af914bd6085c5af68032 to your computer and use it in GitHub Desktop.
Execute async within context of Koa middleware
function loadPageAsync() {
return new Promise(function(resolve, reject) {
request = http.get({
host: 'www.google.com',
path: '/boom'
}, function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
response.body = body;
resolve(response);
});
});
request.on('error', function(err) {
console.log('ERROR');
reject(err);
});
});
}
app.use(function *(){
var response;
try {
response = yield loadPageAsync();
} catch (err) {
console.log(err);
this.throw(err);
}
console.log('Code: ' + response.statusCode);
this.body = response.body;
if (response.statusCode < 200 || response.statusCode >= 300) {
this.throw(response.statusCode, response.statusMessage);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment