繁体   English   中英

异步 function 不等待等待结束

[英]async function not waiting for the await to end

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

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

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

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()里面写什么来完成这项工作。

请帮助大声笑

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM