0

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?

Ryolu
  • 523
  • 3
  • 16
  • 1
    `GetAuthor` is an `async` function, and you need to `await` it as well. – deceze Jul 23 '23 at 09:13
  • 3
    It would help if you consistently used `await` instead of `then` callbacks. E.g. `const r = await fetch(...); const data = await r.json()`. Then it's easy to add an `const author = await GetAuthor(data.author_id)` in there, which you can then use in your HTML. – deceze Jul 23 '23 at 09:15
  • i cant seem to add an await inside of the then, should i change then to await as well? – Ryolu Jul 23 '23 at 09:16
  • 1
    @Ryolu the reason you can't use `await` is that the `.then` callback is not an `async` function. I agree with deceze that you should delete your `.then`'s, replacing them with `await`s. GetArticle is an `async` function, which means you can use `await`. – Nicholas Tower Jul 23 '23 at 09:39

0 Answers0