I am trying to apply my knowledge of working with APIs by making a roleplaying game character generator for my friend. In fact, it is nearly finished, but I now want to add names to the characters using a random person generator API.
I know that my code to call up the API is working:
async function getRandomName () {
try {
const response = await fetch (randomNameUrl);
if (response.ok) {
const jsonResponse = await response.json();
console.log(jsonResponse);
const firstName = jsonResponse.results[0].name.first;
const lastName = jsonResponse.results[0].name.last;
const fullName = `${firstName} ${lastName}`;
return fullName;
}
}
catch(error) {
console.log(error);
}
}
As I can run:
getRandomName().then(x => {console.log (x);})
And I can see a random name generated each time.
I got the above by searching on StackExchange, and I have also searched for a solution to my problem below on Stack Exchange, but have not found a satisfactory answer that I can understand.
So my issue is using the return value (not the Promise, but the string I return) in a constructor for the characters.
The closest I have got is:
class ZeroLevelHero {
constructor() {
this.name = getRandomName().then(value => value);
... }
This means that the value of .name for each object generated with the constructor is “Promise”, and if I look in the Developer Tools I can see the contents of the Promise:
[[Prototype]]:
Promise
[[PromiseState]]
: "fulfilled"
[[PromiseResult]]
: "Orinder Nayak"
What I want is for the .name attribute to have a value of “Orinder Nayak” in this case.
So near and yet so far… Can anyone help?