Looping API calls with Axios and Promises

Viewed 9268

I'm using Axios to make API calls, and for one call I'd like to continue polling the API until I get a response.

However, when I call this function something resolves the promise earlier than expected.

I call the function here:

componentDidMount() {
  api.getUser(this.props.user.id)
  .then((response) => {
    console.log(response);
    this.handleSuccess(response.content);
  })
  .catch((error) => {
    this.handleError(error);
  });
}

And the console.log on line 4 shows undefined. The function does continue polling and stops when it receives valid data.

The function itself:

getUser(id, retries = 0) {
  return axios(getRequestConfig)
  .then((res) => {
    if (res.data && res.data.content.status === 200) {
      return Promise.resolve(res.data); // success!
    } else if (retries >= 15) {
      return Promise.reject(res); // failure
    } else {
      // try again after delay
      delay(1000)
      .then(() => {
        return this.getUser(id, retries + 1);
      })
    }
  })
  .catch(err => err);
}
2 Answers
Related