5

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?

noclew
  • 542
  • 2
  • 5
  • 13
  • @JLRishe I am learning this web application asking here because I am a novice. I am not sure why your are so sarcastic, but I do not believe they did it for fun. Am I correctly answering your question? – noclew Mar 10 '17 at 18:54
  • @JLRishe thanks for your reference. – noclew Mar 10 '17 at 19:16

1 Answers1

5

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);  
});
hya
  • 1,708
  • 2
  • 15
  • 22
  • I see. Then, is it that I always have to use Promise chains once I started Promise? Also, in your modified code, is there a way to assign the contents into the goog variable, i.e., var goog = ? – noclew Mar 10 '17 at 18:51
  • 1
    You could use callbacks, but it aint cool. There are some other ways to deal with asynchronous code like Async, but yeah... once you started Promise, you need to finish it with Promise chain ;) – hya Mar 10 '17 at 18:52
  • 2
    Think this way: in javascript you can't break it once you promise :D – Nelson Teixeira Mar 10 '17 at 18:56
  • 1
    @NelsonTeixeira I see... Once promised, Never break it. – noclew Mar 10 '17 at 19:16
  • to be clear, this isn't unique to promises ... it's the same with any way of dealing with asynchronous operations... callbacks, async/await – Jaromanda X Mar 10 '17 at 23:50