One of my react component's methods is using an async fetch() internally. After fetching the response from the server, it is being converted to JSON, then I perform a check on that JSON string. Finally, I return the result wrapped in a new promise. Here is the code:
fetchCalendarData(offset, length) {
return fetch(this.props.Uri + '?offset=' + offset + '&length=' + length)
.then(response => response.json())
.then((result) => {
if (result.hasOwnProperty('redirect_to_login') && result.redirect_to_login == true) {
window.location.reload(window.globalAppState.base_url + "/login");
}
return Promise.resolve(result);
})
.catch(() => {
return Promise.reject('FAILURE');
});
}
When I call the method, I do it like this:
this.fetchCalendarData(0, 6).then((fetched_calendar_data) => {
this.calendar_data = fetched_calendar_data;
});
The code works, but I am not familiar with promise based flow at all, and those 3 return statements look a little weird to me. I also read about the promise constructor antipattern but am not sure if that applies here. And, is it necessary to return the result wrapped in a new promise, at all?