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?
The function can return a value or a promise object, or can throw an error; these will affect the resolution of the promise object that is returned by then() . A function taking the argument error (or a formula--see Details).
Return valueA Promise that is resolved with the given value, or the promise passed as value, if the value was a promise object. It may be either fulfilled or rejected — for example, resolving a rejected promise will still result in a rejected promise.
Promise resolve() method: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.
Promise.all() The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.
You need to use Promise anyway. You cannot make a synchronous result out of an asynchronous operation in Javascript.
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);
});
};
return get(target);
};
var goog = getWebContent().then(function (res) {
console.log(goog);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With