Skip to content

Instantly share code, notes, and snippets.

@jrgleason
Created January 12, 2016 15:16
Show Gist options
  • Save jrgleason/b512b8fbef712e1a7923 to your computer and use it in GitHub Desktop.
Save jrgleason/b512b8fbef712e1a7923 to your computer and use it in GitHub Desktop.
This is how I handle converting the Node.JS http library over to a promise using Bluebird. This works for both GET and POST.
var http = require('http'),
Promise = require('bluebird');
var PromiseRequest = Promise.method(function(data){
return new Promise(function(resolve,reject){
var request = http.request(data.options, function(res){
var response = null;
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
if(response)
response += chunk;
else
response = chunk;
});
res.on('end', function(){
resolve(JSON.parse(response));
});
}).on("error",reject);
if(data.postData) {
request.write(data.postData);
}
request.end();
});
});
// Useage
function addNode(node) {
var postData = JSON.stringify({
// I am doing this hack because the json var
// is supposed to be a string so I am worried
// about escaping chars
json : JSON.stringify(node)
});
var options = {
host: HOST,
port: PORT,
method: "POST",
path: PATH,
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData),
"Authorization": auth
}
};
return PromiseRequest({
options : options,
postData: postData
})
}
function getLabels() {
var options = {
host: HOST,
port: PORT,
method: "GET",
path: PATH,
headers: {
"Authorization": auth
}
};
return PromiseRequest({
options : options
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment