0

I'm using the node-readability module to grab the title from a URL, but can't seem to use the article variable outside of the callback function.

read('http://howtonode.org/really-simple-file-uploads', function(err, article, meta) {

  console.log(article.title) // this works
  title = article.title

});


console.log(title) // this doesn't work

I would have expected to be able to just set the variable globally and use it as above, but that isn't working... I'm not sure if the issue is something to do with the read function in the module or my code.

suryanaga
  • 3,728
  • 11
  • 36
  • 47
  • 4
    short answer - asynchronism – Jaromanda X Sep 20 '15 at 12:31
  • JaromandaX is correct. When you log the title the response from the request has not come back yet. For fun, try a delay and see what happens (don't use it in your real code though). `setTimeout(function() { console.log(title);}, 3000);` – Tholle Sep 20 '15 at 12:33
  • Okay thanks - That works. So how do I use that variable without setTimeout? – suryanaga Sep 20 '15 at 12:41
  • you can't because asynchronism ... there is no guarantee that the variable will EVER be set ... the settimeout is a kludge at best, it assumes 3 seconds is enough time for the read to work ... this may work 99 times out of a hundred ... – Jaromanda X Sep 20 '15 at 12:51
  • @sanjaypoyzer Don't even try what Tholle suggested, this is totally incorrect approach to the problem. You need to use callback pattern here. – dfsq Sep 20 '15 at 12:51

0 Answers0