【问题标题】:How to catch error in this promise stack?如何在这个承诺堆栈中捕获错误?
【发布时间】:2020-07-17 20:23:08
【问题描述】:

我现在正在尝试编写自己的 Promise。 然后事情是当我堆叠 3 个承诺时,我不知道如何拒绝承诺

这里是代码

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())
  }

如您所见,我正在使用 react-redux。 我在这里想象的是,当我点击提交表单时

首先我会更新项目。然后添加一个新的销售然后重新加载页面

问题是,当我点击提交时,商品已更新,但未进行新销售。但是页面会重新加载。

所以没有进行新的销售,商品减少了。

那么我应该如何更改代码,以便页面不会重新加载&&当出现错误时项目不会更新。

这是动作代码

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,
    });
  });
};
  

【问题讨论】:

  • 好吧,this.props.updateItemthis.props.addSale 是同步调用吗?将这些包裹在Promise 中的原因是什么?
  • 您真的需要重新加载页面吗?如果您不重新加载,用户体验会更好。
  • @goto1 我只是想尝试一下承诺。我认为当我使用 Promise 时,程序不太容易出错
  • @ShadowMitia 问题是当我提交表单时,页面不会重新加载,所以输入数据仍然存在。我正在使用第三方库,所以我选择了简单的方法并刷新页面
  • @Khant 只要它有效^^ 但是您也可以在提交后删除数据。但是一次一个问题^^ 从长远来看,我建议不要一直重新加载页面。

标签: reactjs redux promise


【解决方案1】:
  1. 不要创建新的 Promise 来处理现有 Promise 的 .then()
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() 将被拒绝的 Promise 转换为已解决的 Promise => 如果您需要被拒绝的 Promise,请在 catch 内重新抛出错误(停止执行thens)
      .catch((err) => {
        dispatch(returnErrors(err.response.data, err.response.status))
        throw err
      })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-31
    • 2018-06-08
    • 1970-01-01
    • 2016-01-23
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    相关资源
    最近更新 更多