Im trying to write a code that runs async function and when its done, it runs another piece of code.
I've tried putting the async function in a promise (as seen in the code below) and using the then method without success.
what happens inside the function doesn't really matter but I've included it anyways in case Im mistaking and it does..
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 is the async function Im trying to run before the other functions.
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});
}
}
this is the regular function Im trying to run after the async one
and this is the code:
new Promise((res) => {
this.getDataAndUsername();
res();
}).then(
this.CheckInDataBase(this.state.username)
)
whats happenning right now is that, the this.CheckInDatabase runs before the getDataAndUsername is finished.
await this.getDataAndUsername();?CheckInDataBasemight have a problem: thethis.setState({exist: true});inside the loop might not be propagated before theif (!(this.state.exist))executesasync, so why not giving it theasynckeyword?