Skip to content

Instantly share code, notes, and snippets.

@michael-benin-CN
Forked from coderberry/app.js
Created July 28, 2014 19:22
Show Gist options
  • Save michael-benin-CN/44ea654c2303d7a0707a to your computer and use it in GitHub Desktop.
Save michael-benin-CN/44ea654c2303d7a0707a to your computer and use it in GitHub Desktop.
var express = require('express');
var Promise = require('es6-promise').Promise;
var http = require('http');
var app = express();
var getJSON = function(options) {
console.log('CALLING ' + options['host']);
var promise = new Promise(function(resolve, reject) {
var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
setTimeout(function() {
// Buffer the body entirely for processing as a whole.
var bodyChunks = [];
res.on('data', function(chunk) {
// You can process streamed parts here...
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('RETURNING BODY: ' + body);
resolve(body);
});
}, 3000);
});
req.on('error', function(e) {
console.log('RETURNING ERROR: ' + e.message);
reject(e);
});
});
return promise;
};
app.get('/', function(req, res) {
var promises = [
getJSON({ host: 'addressbook-api.herokuapp.com', path: '/contacts.json' }),
getJSON({ host: 'api.zippopotam.us', path: '/us/90210' })
];
Promise.all(promises).then(function(results) {
console.log(results);
res.send('DONE!');
}).catch(function(reason) {
console.log(reason);
res.send(reason);
});
});
var server = app.listen(8000, function() {
console.log('Listening on port %d', server.address().port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment