Reputation: 299
I am attempting to build a global API request function considering the repetitiveness of it. The problem I have is despite the responseBody object not being null when the function ends, the response seems to be null?
I can only assume this is in part due to the object being returned before it is updated.
Here is the function:
export function restRequest(url, method, content, body) {
fetch(API_BASE_URL + url, {
method: method,
headers: new Headers({
'Content-Type': content,
'Access-Control-Request-Method': method,
// 'Authorization': localStorage.getItem(ACCESS_TOKEN)
}),
body: body
}).then(
function (response) {
response.json().then((data) => {
let json = JSON.parse(JSON.stringify(data));
let responseBody = {
code: response.status,
body: json
};
//at this point the responseBody is not null
return responseBody;
});
}
)
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
However if I make a call:
let response = restRequest('/app/rest/request', 'GET', 'application/json;charset=UTF-8', null);
response is always null.
What is the best way to handle this?
Upvotes: 1
Views: 820
Reputation: 370689
It's asynchronous, so any call of restRequest
will not immediately return the responseBody
= you need to properly chain the promises, and call .then
on the restRequest
call. Return the fetch
call from the restRequest
function, and avoid the promise-callback antipattern by returning response.json()
immediately, rather than nesting a .then
inside it:
export const restRequest = (url, method, content, body) => (
fetch(API_BASE_URL + url, {
method: method,
headers: new Headers({
'Content-Type': content,
'Access-Control-Request-Method': method,
// 'Authorization': localStorage.getItem(ACCESS_TOKEN)
}),
body
})
.then(response => Promise.all([response.status, response.json()])
.then(([code, body]) => ({ code, body }))
.catch(function(err) {
console.log('Fetch Error :-S', err);
})
);
then do
restRequest('/app/rest/request', 'GET', 'application/json;charset=UTF-8', null)
.then(response => {
// do stuff with response. (if there was an error, response will be undefined)
});
Upvotes: 3