2

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!

9
  • Try to declare your res variable outside the async function. Commented Mar 16, 2021 at 4:08
  • 3
    @AbdullahKhan, no that would be unnecessary. Commented Mar 16, 2021 at 4:14
  • Are you awaiting at the call site? I.e. const result = await queryApi(query) versus const result = queryApi(query) Commented Mar 16, 2021 at 4:20
  • I'm fairly sure the problem is stemming from an improper use of fetch(). Fetch returns a promise, which you can't just call .json() on. Commented Mar 16, 2021 at 4:22
  • @David Oh really? The code works synchronously. Commented Mar 16, 2021 at 4:24

2 Answers 2

5

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>.

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

Comments

1

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;
        }

1 Comment

Yeah I thought that too but then thought typos?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.