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!
resvariable outside the async function.const result = await queryApi(query)versusconst result = queryApi(query)fetch(). Fetch returns a promise, which you can't just call.json()on.