Last active
April 1, 2016 17:49
-
-
Save coderberry/36b266dc2c0f4a93c471 to your computer and use it in GitHub Desktop.
Example of using Ember's RSVP in Node to perform asynchronous API calls.
This file contains hidden or 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
| var express = require('express'); | |
| var RSVP = require('rsvp'); | |
| var http = require('http'); | |
| var app = express(); | |
| var getJSON = function(options) { | |
| console.log('CALLING ' + options['host']); | |
| var promise = new RSVP.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' }) | |
| ]; | |
| RSVP.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