I am wring a getWebContent function that returns the content of a webpage using Promise (I am also using Request module).
The way I'd like to use this function is var content = getWebContent(), so that content variable contains the data of the requested website. I started as follows:
var request = require('request')
var getWebContent = function () {
target = 'http://www.google.com';
var result = null;
var get = function (url) {
return new Promise(function (resolve, reject) {
function reqCallback(err, res, body) {
if (err) reject(err);
else resolve(body);
};
request(url, reqCallback);
});
};
get(target).then(function (res) {
result = res;
console.log(res);
});
return result;
};
var goog = getWebContent();
console.log(goog)
However, this code does not work, because the function returns result variable, which is null, before the Promise object is resolved. Could you please let me know how I should fix my code so that it works as intended?