-1

Im trying to get a text from a website and put the text in a variable. I then want to have an if statement, if the variable == "something" then do function. As of now, here is my code, I cannot seem to define a variable in the function. If I do, I cannot use the variable outside the function for my if statement

const superagent = require('superagent');

(async function(){
  const response = await superagent.get('https://www.google.com')
  var text = (response.text)
})();

if (text == "something"){
    //do something
}

My code above returns "text is not defined"

nem035
  • 34,790
  • 6
  • 87
  • 99
Gem Clash
  • 107
  • 1
  • 7
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – nem035 Dec 18 '18 at 02:20

1 Answers1

0

There are 3 problems:

  1. You are not waiting for the async function to finish before trying to read text, so text is not available at the point you do console.log(text)

  2. text is not defined outside the async call and therefore not visible outside of it. Even if you fix the async call, it will still not be visible

  3. It is not possible to await an async function outside an async context. So there is no way for you to await that self executing function

Your option?

Make the async function return the value you wanted, and get this as text;

(async function(){
  const response = await superagent.get('https://www.google.com')
  return response.text
})().then(function(text) {
    console.log(text);
}

Other options exist, but there is no escaping that async function. Any value returned has to either be assessed within an async context or used in the way I've shown above

smac89
  • 39,374
  • 15
  • 132
  • 179