首页 > 解决方案 > 使函数等待直到第一个函数完成运行

问题描述

我的 React App 中有这个功能。它调用了一些其他函数。一切正常,除了我需要在运行.then(() => this.getHCAid())前完成.then(() => this.addDocsList())。我无法做到这一点。我确定这很简单,我只是不知道如何。

createHCA() {
      fetch(API_URL + `/hca/create`, {
        method: "PUT",
        body: JSON.stringify({
          client: this.state.client,
          short: this.state.short,
        }),
        headers: { "Content-Type": "application/json" },
      })
        .then((res) => {
          if (!res.ok) {
            throw new Error();
          }
          return res.json();
        })
        .then((data) => console.log(data))
        .catch((err) => console.log(err))
        .then(() => this.getHCAid())      <--- Need this to complete
        .then(() => this.addDocsList())   <--- Before this runs
        .then(() => this.getAllHCAs());
        this.setState({ showHide: false});
  }

标签: javascriptreactjs

解决方案


听起来这里有两个问题。

首先是您的函数听起来像数据库查询或更新,它们将是异步的,因此如果没有被告知等待,您不能依赖循环中的下一步来访问返回的任何数据。

您尝试提出的解决方案(在其中一种then方法中设置状态)也不起作用,因为它也对查询进行批处理并异步处理它们,并且下一步也无法访问该数据。

因此,理想情况下,您可能应该做的是使用promise从 中返回 id getHCAid,然后将其传递到addDocsList其中也返回 promise 等。

这是一个使用async/await.

getHCAid() {
  return new Promise((res, rej) => {
    // Do DB process, get an id
    res(id);
  });
}

async getData() {
  const response = await fetch(API_URL);
  const data = await response.json();
  const id = await this.getHCAid();
  const list = await this.addDocsList(id);
  const hcas = await this.getAllHCAs();
  this.setState({ showHide: false });
}

推荐阅读