I am trying to request for an article from the server, requesting for the author's name again after getting the article's information, which contains the author's id. I seem to be getting what I need in the console.logs
scattered around, but I see a [object Promise]
in my article's heading.
Here is the function that gets my article:
async function GetArticle() {
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: articleID })
};
fetch("/get-article", options)
.then((response) => response.json())
.then((data) => {
console.log(data);
const newElement = document.createElement("div");
newElement.classList.add("w-75");
newElement.classList.add("m-4");
newElement.innerHTML = `
<h2>${data.title} uploaded by ${GetAuthor(data.author_id)}</h2>
`;
articleParent.appendChild(newElement);
})
.catch((error) => console.error("Error:", error));
}
and here is the function that gets the corresponding author's name from the server:
async function GetAuthor(author_id) {
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: author_id }),
};
return await fetch("/user/get-authors", options)
.then((response) => response.json())
.then((data) => {
console.log(data.author_name)
return data.author_name;
});
}
From what I understood from my little experience with async stuff, using .then
is supposed to yield the results I expected. It has worked for my other functions, just not in this nested async, why is that?