javascript - 在javascript中的异步函数之后运行函数
问题描述
我试图编写一个运行异步函数的代码,完成后,它运行另一段代码。
我尝试将 async 函数放入一个 Promise 中(如下面的代码所示)并使用该then
方法但没有成功。
函数内部发生的事情并不重要,但无论如何我都已经包含了它,以防我弄错了,它确实..
getData = async(file) =>{
let data = await fetch(file);
data = await data.text();
return(data);
}
getDataAndUsername = async() => {
this.setState({data: JSON.parse(await this.getData("/getData"))});
this.setState({username: await this.getData("/user")});
console.log('done');
}
getDataAndUsername 是我试图在其他函数之前运行的异步函数。
CheckInDataBase = (username) => {
console.log('checking In DataBase');
this.state.data.forEach((element)=>{
if(element.username === username){
this.setState({exist: true});
}
});
if (!(this.state.exist)){
axios.post('/createUser', {"username": username, "status": "Working"});
this.setState({exist: true});
}
}
这是我试图在异步之后运行的常规功能
这是代码:
new Promise((res) => {
this.getDataAndUsername();
res();
}).then(
this.CheckInDataBase(this.state.username)
)
现在发生的事情是 this.CheckInDatabase 在 getDataAndUsername 完成之前运行。
解决方案
被定义为async
,你getDataAndUsername
的已经是一个 Promise,没有必要把它包装在new Promise()
. 你可以这样做:
this.getDataAndUsername().then( _ => {
this.CheckInDataBase(this.state.username);
})
它应该工作。
为什么你的代码一开始就不起作用
你正在用这个创建一个新的承诺:
new Promise((res) => {
this.getDataAndUsername();
res();
}) ...
在那里,你打电话this.getDataAndUsername()
,但忽略它是否解决。该代码将 res
立即调用,因此在解决checkInDatabase
之前被调用。getDataAndUsername
你冷,相反,等待getDataAndUsername
解决:
new Promise((res) => {
return this.getDataAndUsername().then(_ => {res()})
}) ...
关键是等待承诺解决使用then
,并添加return
.
但是,如上所述,没有必要这样做,因为getDataAndUsername
它已经是一个 Promise。
推荐阅读
- r - R中的Separate()函数不根据选择的字符分隔符进行拆分
- python - 如何将两个不同字典中的值相乘
- eclipse - Eclipse - Yiiclipse 安装错误
- android - 如何知道复选框是否未使用按钮选中?
- sql - PosgreSQL 以递归方式选择不同的总和
- python - 我想使用列表中列表的计数进行进一步计算
- ios - 如何向导航栏添加渐变配色方案?
- java - 如何覆盖在证书到期时引发异常的 BouncyCastle 方法?
- amazon-web-services - 如何将 DNS 从 NIC.ar 委托给 AWS-EC2
- python-3.x - pymongo.errors.ConfigurationError:必须安装“dnspython”模块才能使用 mongodb+srv:// URI