I have these 3 functions that need to run in order. However, since the first function has a loop in it, the 2nd and 3rd functions are finishing before the data from the 1st function is available. How can I refactor this to guarantee each one completes in order before the next starts? In the past using .then has given me what I need. But this time it's not completing in the right order.
mainFunction() {
fetch(API_URL + `/dataToGet`)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((result) => {
this.setState({data: result}, () => this.1stFunction());
console.log(result);
})
.catch((error) => {
console.log(error);
})
.then(this.2ndFunction())
.catch((error) => {
console.log(error);
})
.then(this.3rdFunction());
}
firstFunction(){
for (let i = 0; i < data.length; i++){
for (let j = 0; j < 8; j++){
//...grabbing data and saving to variables to be used in next steps...
}
}
}
secondFunction(){
... wait until firstFunction is completed and then do something with data...
}
thridFunction(){
... wait until secondFunction is complete and then do something else with that data...
}