javascript - 使函数等待直到第一个函数完成运行
问题描述
我的 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});
}
解决方案
听起来这里有两个问题。
首先是您的函数听起来像数据库查询或更新,它们将是异步的,因此如果没有被告知等待,您不能依赖循环中的下一步来访问返回的任何数据。
您尝试提出的解决方案(在其中一种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 });
}
推荐阅读
- python - AWS - 使用公共 IP 自动修复 EC2
- php - 在cakephp中登录不正确,即使一切都是正确的
- android - 如何对数组列表中存在的时间进行排序?
- javascript - Bluebird 取消等待
- ionic3 - 类名中带有前缀的 ngClass 提供空间
- excel - 从子文件夹 excel 文件中复制非连续单元格(A1、B5、C6)的数据并粘贴到父文件夹中找到的主文件中
- python - 无法加载安装在虚拟环境中的模块
- html - 如何使用html和css并排放置两个选择属性(以不同的形式)
- xamarin - Xamarin 表单 - 导航推送 - 分屏
- python - 爬取数据基于自动访问基于href的多个页面