簡體   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