1

I am trying to get Data over my API-Endpoint and want to populate my page with the data. I know that I have to use async/await to be sure that the variable was filled. Therefore I wrote the following lines and want to know that it is possible to write an async function inside an async function. It is working but I am not sure if it is the correct way:

async function getRoom(id) {
    const response = await fetch('/api/zimmer/' + id);
    if (!response.ok) {
        const message = `An error has occured: ${response.status}`;
        throw new Error(message);
    }
    const rooms = await response.json();
    console.log(rooms);
    return rooms;
}

async function getSelectedItem() {
    var e = document.getElementById("Objekt");
    if (e.value > 0) {
        zimmer_select.disabled = false;
        var response = await getRoom(e.value);
        console.log(response);
        response.forEach(function(element) {
            
            console.log(element);
        });
    } else {
        zimmer_select.disabled = true;
    }
    console.log(e.value);
}
3
  • There's nothing obviously wrong here. If it's working as you expect then I see no issue. Commented Mar 21, 2022 at 21:24
  • Where is the async function inside another async function? I can't see it. Are you talking about calling an async function inside an async function? That's the main (or only) use-case for async/await. Commented Mar 21, 2022 at 21:42
  • what do you mean by "the correct way"? it looks fine.. idk what zimmer_select is but it seems you know what you're doing.. what's the problem ;-; Commented Mar 21, 2022 at 21:52

1 Answer 1

1

I think it is fine to use it this way actually. If you think about, sometimes you have to use async inside async. What if you have some async function which fetches data and you have to loop over that data and await for something. If you loop it with for each you won't be able to use await, so you should put async before it. So as long it's clean and have no other way, I think it is fine to use async inside async.

Sign up to request clarification or add additional context in comments.

1 Comment

Where do you see async inside async in the question?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.