【问题标题】:async function not waiting for the await to end异步函数不等待等待结束
【发布时间】:2020-06-10 18:02:45
【问题描述】:

我试图在我的代码中添加一个async/await 以让应用程序等待执行一个函数来调用另一个函数,但我似乎无法弄清楚我的代码哪里出错了.

我在 redux 操作中有一个 API 调用,这就是操作

export const editSecondaryCategory = (text) => {
  return (dispatch) => {
    let obj = {
      text
    };
    axios
      .put(
        `${ROOT_URL}/...`,
        obj
      )
      .then(() => {
        dispatch({ type: EDIT_NOTE, payload: [...annotations] });
        dispatch(loadAllAnnotations(cid, uuid));
      })
      .catch((error) =>
        dispatch(
          notifSend({
            message: error.message,
            kind: "danger",
            dismissAfter: 2000,
          })
        )
      );
  };
};

我希望在我的组件中等待此操作完成后调用另一个函数来更新状态。理想情况下,它应该是这样的(我猜?):

async updateCategory() {

    // do the thing I have to wait for
    const propsUpdate = await this.props.editSecondaryCategory(text);

    // if you've done the thing then call the function to update the state
    if (updatedCat) {
      this.updateStateArray();
    }

  }

在用户完成信息编辑后,我会在我的组件中调用this.updateCategory()。 显然,此代码不起作用。我知道这是错的,我只是不知道为什么。基本上我不知道在updateCategory() 里面写什么来完成这项工作。

请大家帮忙看看

【问题讨论】:

    标签: javascript reactjs async-await react-redux


    【解决方案1】:

    您需要重写 editSecondaryCategory 函数以使其异步。

      export async function editSecondaryCategory(text){
      return (dispatch) => {
        let obj = {
          text
        };
        axios
          .put(
            `${ROOT_URL}/...`,
            obj
          )
          .then(() => {
            dispatch({ type: EDIT_NOTE, payload: [...annotations] });
            dispatch(loadAllAnnotations(cid, uuid));
          })
          .catch((error) =>
            dispatch(
              notifSend({
                message: error.message,
                kind: "danger",
                dismissAfter: 2000,
              })
            )
          );
      };
    };
    

    目前,您的函数不是异步函数,请进行上述更改并检查。

    【讨论】:

    • 不正确,它只需要返回一个承诺。一个函数不需要是“异步的”来返回一个承诺。您的更改实际上也不会导致它等待 axios 调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2019-06-16
    • 2018-02-03
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多