0
var content = 'now - not content';

const getHtmlCode = function(){
  request(url, function(req, resp, body){
    content = body;
  });
  return content;
};

console.log(getHtmlCode()); // >> now - not content

In console i can see /now - not content/ because request to site takes 2-3 second.

Bad solution: i can add setTimeout on return, but this is very bad way.

How i can wait before return content ?

John Laybues
  • 83
  • 1
  • 6
  • 2
    You need to either use promises or async/await. There are a ton of really good articles out there as well as several good replies on this site that should help you. – Adam H Aug 16 '18 at 21:46

1 Answers1

2

In your case perform the console.log() operation in the callback, i.e.

var content = 'now - not content';

const getHtmlCode = function(){
    request(url, function(req, resp, body){
        console.log(body);
    });
};

getHtmlCode();

If you prefer to use a promise you could try the code below;

function getHtmlCode(){
    return new Promise ((resolve, reject)=>{
        request(url, function(req, resp, body){
            if(!body) reject({message: "No body"});
            resolve(message);
        });
    });
}

getHtmlCode().then((body)=>{
    console.log(body)
}).catch(err=>{
    console.log(err);
})
Xixis
  • 881
  • 6
  • 8