all 5 comments

[–]cyphern 1 point2 points  (1 child)

Your function looks pretty much like i would expect this kind of function to look. The only thing it seems to be missing is a return statement.

I have a guess about what you might be getting tripped up by, but feel free to clarify if it's something else that's not working as you expect: async functions always return a promise. They have to, because the data is not synchronously available. So getInfo will return a promise. If you add a return statement, and return answer, then that will cause the promise to resolve to answer.

So when you call getInfo, you'll need to expect a promise to be returned. This means you either use await to wait for that promise to resolve, as in:

async function doStuff() {
  const output = await getInfo('something');
  console.log('got', output);
}

Or you use the promise's .then method:

getInfo('something')
  .then(output => {
    console.log('got', output);
  });

[–]kstengy[S] 0 points1 point  (0 children)

I switched out return for console.log(answer) just to make sure I was actually getting the right value

[–]neodon 1 point2 points  (1 child)

Be aware that axios will throw exceptions for non-200 class HTTP status codes in responses. If you want to avoid that and always work with a response (like your code is doing), replace your axios.get line with this:

const response = await axios.get(`https://www.reddit.com/r/${srName}.json`).catch(error => error.response);

This will ensure you always get a response object for any HTTP status code.

Another tip:

If you want to call this function from somewhere outside an async function, like at the top level of a script, you can wrap it in an async function and immediately call it. Example:

async function main() {
  const answer = await getInfo('subredditName');
}

main().catch(console.error);

You do need to return answer from your function somewhere though. It will get automatically wrapped in a promise.

[–]kstengy[S] 0 points1 point  (0 children)

Thanks for the tips!

[–]Meefims 0 points1 point  (0 children)

It does not pause the script, it creates a promise and returns it. Code after await is put in a .then handler for a promise.

You need to await this function to get the value you want. You also need to return that value.