get request with promise in nodejs
'use strict';
var get = function get(url) {
// return new pending promise
return new Promise(function (resolve, reject) {
// http, https
var lib = require(url.match(/^(https|http)/));
var request = lib.get(url, function (response) {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
var body = [];
response.on('data', function (chunk) {
return body.push(chunk);
});
// resolve promise
response.on('end', function () {
return resolve(body.join(''));
});
});
request.on('error', function (err) {
return reject(err);
});
});
};
Written by Bruce Lim
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Nodejs
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#