Skip to content

Instantly share code, notes, and snippets.

@anandsunderraman
Last active October 19, 2016 14:03
Show Gist options
  • Save anandsunderraman/a57b7117ddea474c3bc9 to your computer and use it in GitHub Desktop.
Save anandsunderraman/a57b7117ddea474c3bc9 to your computer and use it in GitHub Desktop.
Node.js request with Q promises
//import the http library
var http = require('http'),
//npm install q before requiring it
Q = require('q');
//a js object with options
var googleNewsOptions = {
hostname: 'ajax.googleapis.com',
path: '/ajax/services/search/news?v=1.0&q=nodejs',
method: 'GET'
};
/**
* wrapper for http request object
* @param {Object} requestOptions
* @return Promise Object
*/
function promisedRequest(requestOptions) {
//create a deferred object from Q
var deferred = Q.defer();
var req = http.request(requestOptions, function(response) {
//set the response encoding to parse json string
response.setEncoding('utf8');
var responseData = '';
//append data to responseData variable on the 'data' event emission
response.on('data', function(data) {
responseData += data;
});
//listen to the 'end' event
response.on('end', function() {
//resolve the deferred object with the response
deferred.resolve(responseData);
});
});
//listen to the 'error' event
req.on('error', function(err) {
//if an error occurs reject the deferred
deferred.reject(err);
});
req.end();
//we are returning a promise object
//if we returned the deferred object
//deferred object reject and resolve could potentially be modified
//violating the expected behavior of this function
return deferred.promise;
};
//incoking the above function with the request options
promisedRequest(googleNewsOptions)
.then(function(newsResponse) { //callback invoked on deferred.resolve
console.log(JSON.stringify(newsResponse));
}, function(newsError) { //callback invoked on deferred.reject
console.log(newsError);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment