The problem is that you never return the promise chain from your function. So your async
function's return value is a promise fulfilled with undefined
, just like a non-async
function with no return
returns undefined
.
There's another issue with that code: If you're using an async
function, generally it's best to use await
rather than .then
, .catch
, etc. Also, don't catch rejection in the function; instead, let the caller handle it so it knows something went wrong.
So for instance:
async function get_highlights() {
const response = await fetch("/api/v1/gethighlights/"+network_number);
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
}
But if you really want to handle errors inline:
async function get_highlights() {
const response = await fetch("/api/v1/gethighlights/"+network_number);
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
try {
return await response.json();
} catch { // Note: ES2019 allows optional `catch` bindings
this.dataError = true;
}
}
but again I don't recommend that, because the caller has to check to see whether they got data or undefined
when the promise is fulfilled (or check dataError
, I guess :-) ).
Side note: Note that in the first example, which doesn't have a try
/catch
, I did return response.json();
but in the second example, where the return
is inside a try
/catch
, I did return await respohnse.json();
. The reason is that when returning a promise at the top level of the function, there's no effective difference between return somePromise
and return await somePromise
, but that's not true if the code is in a control block like a try
/catch
. Having the await
ensures that our catch
block is executed if the promise is rejected. Not having it wouldn't ensure that.