ThirdGhostHand
ThirdGhostHand

Reputation: 397

Struggling with asynchronous JavaScript code

I'm trying to get this function to asynchronously call an API and return the response's JSON. However, the function returns nothing, before the API call has returned and populated res.

I'm confused about the proper usage of asynchronous JavaScript in this use case.

From my understanding, once async has been declared in a function, then the code will pause whenever it hits an await until the await has returned a promise. But that obviously isn't the case. What am I missing?

        let queryApi = async (query) => {
            const url = "http://localhost:3000/test";
            const response = await fetch(url)

            const res = await response.json();
            return res;
        }

Thanks friends!

Upvotes: 2

Views: 138

Answers (2)

Darkhan
Darkhan

Reputation: 21

Here you have some problems with your braces. Actually you need something like this:

        const queryApi = async (query) => {
            const response = await fetch(query);
            const res = await response.json();
            return res;
        }

Upvotes: 1

quicVO
quicVO

Reputation: 888

Yes, that is how Promises work. You must call asynchronous code from an asynchronous setting or a top-level module. So let's say you have the following code (adjusted).

let queryApi = async (query) => {
    const response = await fetch(query);
    const res = await response.json();
    return res;
}

You can call it like so:

let result = await queryApi('https://www.example.com');
console.log(result);

It must be inside an asynchronous function OR in a <script type='module'></script>.

Upvotes: 5

Related Questions