I have a fetch()
call in function myFetch()
(returns the fetch
's return value), and would like to wrap it in another function callApi()
. My goal is to make callApi()
return a Promise, such that:
- A "resolve" state indicates success (the fetch call returned response.ok / HTTP 200).
- In this case, I would like the value (of promise) to be the body/text of the response.
- A "reject" state indicates any failure during the process, which could be:
- There is something wrong with the fetch call, e.g. a GET request with body.
- In this case, I would like the message of reject to be that error.
- The fetch succeeded, but the upstream response is not HTTP 200.
- In this case, I would like the message of reject to be
status_code: body
wherestatus_code
andbody
are both from the HTTP response. - In fact, it does not have to be in this form, as long as the caller of
callApi()
can reconstruct this same message.
- In this case, I would like the message of reject to be
- There is something wrong with the fetch call, e.g. a GET request with body.
However, I do not know how to write the callApi()
function. My attempt only ended up with this (where myFetch()
is the call to fetch
):
return new Promise(
(resolve, reject) => {
myFetch()
.then((response) => {
if (response.ok) {
resolve(response);
} else {
reject(`${response.status}: ${response.text}`);
}
}, (error) => {
reject(error);
});
}
);
As you see, response.text
is a Promise, but I need the string there.
How can I achieve my goal?
In addition, if I also need to receive JSON response (from the fetch
), will there be any difference?