我正在尝试编写运行异步函数的代码,当它完成后,它会运行另一段代码。
我已经尝试将异步函数放在一个 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);
})
它应该可以工作。
为什么你的代码一开始就不起作用
你正在用这个创建一个新的 promise :
new Promise((res) => {
this.getDataAndUsername();
res();
}) ...
在那里,您调用了 this.getDataAndUsername()
,但忽略了它是否已解析。该代码将立即调用 res
,因此 checkInDatabase
在 getDataAndUsername
解析之前被调用。
你冷,相反,等待 getDataAndUsername
解析:
new Promise((res) => {
return this.getDataAndUsername().then(_ => {res()})
}) ...
重点是使用 then
等待 promise 解决,并添加 return
。
但是,如上所述,没有必要这样做,因为 getDataAndUsername
已经是一个 Promise。
关于javascript - 在javascript中异步函数之后运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546594/