How to catch error in this promise stack?

Viewed 62

I am now trying to write my own Promises. Then thing is that I don't know how to reject the promise when I stack 3 promises

Here are the codes

const onFinish = (values) => {

  const UpdateItem = () => {
    return new Promise((resolve, reject) => {
      // Update the item
      resolve(this.props.updateItem(this.props.item.items, index));
    });
  };
  const AddSale = () => {
    return new Promise((resolve, reject) => {
      // Add To Sale
      resolve(this.props.addSale(newSale));
      // ;
    });
  };
  const reloadPage = () => {
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(window.location.reload());
      },1000)
    });
  };

  UpdateItem()
    .then(() => AddSale())
    .then(() => reloadPage())
  }

As you can see I am using react-redux. What I imagining here is that When I hit submit the form

First I will update then item. then add a new sale then reload the page

The problem is that when I hit submit an item is updated but the new sale is not made. But the page is reloaded.

So the new sale not made and the item is decreased.

So how should I change the code so that the page will not reload && the item is not updated when there is an error.

Here is the Actions code

export const addSale = (sale) => (dispatch, getState) => {
    // will hit reducer
    // console.log(sale)
    Axios.post("/api/sales", sale, tokenConfig(getState))
      .then((res) => {
        dispatch({
          type: ADD_SALE,
          // res.data is new sale
          payload: res.data,
        });
      })
      .catch((err) => {
        dispatch(returnErrors(err.response.data, err.response.status));
      });
  };

export const updateItem = (item, index) => (dispatch, getState) => {
  // will hit reducer
  // console.log(item[index]);
  // console.log(item);
  // console.log(index)
  Axios.post(
    `/api/items/update/${item[index]._id}`,
    item[index],
    tokenConfig(getState)
  ).then((res) => {
    dispatch({
      type: UPDATE_ITEM,
      // res.data is new item
      payload: res.data,
    });
  });
};
  
1 Answers
  1. don't create new Promises to handle .then() of an existing Promise
const onFinish = (values) => {
  const updateItem = () => this.props.updateItem(this.props.item.items, index)
  const addSale = () => this.props.addSale(newSale)
  const reloadPage = () => window.location.reload()

  updateItem()
    .then(addSale)
    .then(reloadPage)
}
  1. catch() converts a rejected Promise into a resolved one => re-throw the error inside catch if you need a rejected Promise (to stop executing following thens)
      .catch((err) => {
        dispatch(returnErrors(err.response.data, err.response.status))
        throw err
      })
Related