Skip to content

Instantly share code, notes, and snippets.

@coderberry
Created July 28, 2014 13:39
Show Gist options
  • Save coderberry/4d154cdc25c339dfcabe to your computer and use it in GitHub Desktop.
Save coderberry/4d154cdc25c339dfcabe to your computer and use it in GitHub Desktop.
Example of using es6-promise in Node to perform asynchronous API calls.
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