-
-
Save jdriscoll/af914bd6085c5af68032 to your computer and use it in GitHub Desktop.
Execute async within context of Koa middleware
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
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