Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var async = require('async');
- var request = require('request');
- app.get('endpoint',function(req, res){
- async.series([
- function(callback){request.get('url',callback)},
- function(callback){request.get('url2',callback)},
- function(callback){request.get('url'3,callback)},
- ],
- function(err,results){
- //handle error
- //results is an array of values returned from each one
- var processedData = {
- a: results[0],
- b: results[1],
- c: results[2]
- };
- res.send(processedDAta)
- })
- })
- app.get('/endpoint',function(req, res){
- var dataSources = ['url1', 'url2',url3];
- var requestData = [];
- processRequestData = function(){
- //do you stuff here
- res.send(processedData);
- };
- dataSources.forEach(function(dataSource){
- request.get(dataSource,function(err,result){
- //handle error
- requestData.push(result);
- if(requestData.length == dataSources.length){
- processRequestData();
- }
- })
- })
- });
- app.get('/resource', function(req, res){
- // object to send back in the response
- var results = {};
- // helper function to make requests and handle the data to results object
- var getData = function(url, propertyName, next){
- http.get(url, function(err, data){
- // let async.js know if there is an error
- if(err) return next(err);
- // save data to results object
- results[propertyName] = data;
- // async.js needs us to notify it when each operation is complete - so we call the callback without passing any data back to
- next();
- });
- };
- // array of operations to execute in series or parallel
- var operations = [];
- operations.push(function(next){
- getData('http://url-one', 'users', next);
- });
- operations.push(function(next){
- getData('http://url-two', 'posts', next);
- });
- // async.js has a few options on how to execute your operations - here we use series
- async.series(operations, function(err){
- if(err){
- throw err;
- }
- // if we get to this point, all of the operations have exectued and called
- // next() without any errors - send the response with a populated results object.
- res.send(results);
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement