Your code is almost perfect. To retell a bit, you need a function that wraps http.request with this form:
function httpRequest(params, postData) { return new Promise(function(resolve, reject) { var req = http.request(params, function(res) { // on bad status, reject // on response data, cumulate it // on end, parse and resolve }); // on request error, reject // if there post data, write it to the request // important: end the request req.end() }); }
Note the addition of params and postData so that it can be used as a general purpose request. And note that the last line of req.end() - which should always be called - was missing from the OP code.
Applying these pair changes to the OP code ...
function httpRequest(params, postData) { return new Promise(function(resolve, reject) { var req = http.request(params, function(res) { // reject on bad status if (res.statusCode < 200 || res.statusCode >= 300) { return reject(new Error('statusCode=' + res.statusCode)); } // cumulate data var body = []; res.on('data', function(chunk) { body.push(chunk); }); // resolve on end res.on('end', function() { try { body = JSON.parse(Buffer.concat(body).toString()); } catch(e) { reject(e); } resolve(body); }); }); // reject on request error req.on('error', function(err) { // This is not a "Second reject", just a different sort of failure reject(err); }); if (postData) { req.write(postData); } // IMPORTANT req.end(); }); }
This is not tested, but it should work fine ...
var params = { host: '127.0.0.1', port: 4000, method: 'GET', path: '/api/v1/service' }; // this is a get, so there no post data httpRequest(params).then(function(body) { console.log(body); });
And these promises can also be chained ...
httpRequest(params).then(function(body) { console.log(body); return httpRequest(otherParams); }).then(function(body) { console.log(body); // and so on });