Skip to content

Instantly share code, notes, and snippets.

@davidhooey
Forked from anandsunderraman/promisedRequest.js
Created October 19, 2016 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhooey/cf37104a6bd930ac386b1d10ca47ae88 to your computer and use it in GitHub Desktop.
Save davidhooey/cf37104a6bd930ac386b1d10ca47ae88 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