0

I'm trying to learn how to use axios from this site: Asynchronous Javascript using Async - Await

async function getGamerDescription() {
    const text = await axios.get(`/api/gamer/${id}/gamerBio`);
    return text.data;
}

console.log("bio: ", getGamerDescription());

gives me:

bio:  Promise {<pending>}

If I put the console.log INSIDE the getGamerDescription() function, then it writes out the bio text that I need.

But I need to assign the bio text to a variable so I can display it on my website.

Is there a way to do that?

I found some other SO questions:

Axios returns promise pending

My call async/await returns a Promise {} in my actions

But they didn't help.

I just want to be able to get the value so I can assign it to a variable.

SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185
  • Probably a duplicate of https://stackoverflow.com/questions/49938266/how-to-return-values-from-async-functions-using-async-await-from-function – saif iqbal Aug 11 '21 at 20:25

1 Answers1

0

An async function automatically becomes a promise, so in this case getGamerDescription is actually a promise, so you have to use await when logging it, but await can only be called inside an async function, so try this:

async function getGamerDescription() {
    const text = await axios.get(`/api/gamer/${id}/gamerBio`);
    return text.data;
}

(async () => console.log("bio: ", await getGamerDescription()))();

Notice I wrapped the console.log inside an async IIFE and used await inside the console.log, this is because I'm treating the async function getGamerDescription as a promise. If you wanted to assign it to a variable you need to do that using await inside another async function

Ameer
  • 1,980
  • 1
  • 12
  • 24
  • but how would assign it to a variable? Like if I need to display the bio on my website, that means my whole component would need to be `async`? – SkyeBoniwell Aug 11 '21 at 20:24
  • Inside another async function `const something = await getGamerDescription()` – Ameer Aug 11 '21 at 20:33