2
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

but am not sure if that applies here. And, is it necessary to return the result wrapped in a new promise, at all?

Yes, that applies here.

No, returning Promise.resolve() is not necessary. .then() returns a new Promise object. Use

return result

within the function passed to .then().

Note, a value returned from .catch() results in a resolved Promise. Depending on how errors are handled an error could be thrown (withing {} of a function).

this.fetchCalendarData(0, 6).then((fetched_calendar_data) => {
    this.calendar_data = fetched_calendar_data;
});

should include the second parameter to .then() to handle potential error

.then((fetched_calendar_data)=>{}, err=>{/* handle error */})

given then Promise.reject() is returned from .catch(), or .catch() should be chained to .then()

.then((fetched_calendar_data)=>{}
.catch(err=>{/* handle error */})

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 result;
  })
  .catch(() => {
    throw new Error('FAILURE');
  });
}

this.fetchCalendarData(0, 6)
.then(fetched_calendar_data => {
  this.calendar_data = fetched_calendar_data;
})
.catch(err => console.error(err));
\$\endgroup\$
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.