Reputation:
How to run the function FinalExecution only after the execution of all Async calls within the forEach function?
doit=()=>{
cart.forEach(async(i)=>{
await axios.get(`localhost.........`})
.then(({data})=>{
this.setState({data})})
.catch(()=>{
this.setState({error:true})});
})
this.finalExecution();
}
finalExecution=()=>{
.......
.......
}
Upvotes: 1
Views: 203
Reputation: 88
Use for loop
or Promise.all()
cart = [1, 2, 3]
class Cat {
constructor() {
this.setState = (param) => {
// console.log(param)
}
}
doit = async () => {
for (const i of cart) {
await axios.get(`https://jsonplaceholder.typicode.com/todos/${i}`)
.then(({ data }) => {
this.setState({ data })
})
.catch(() => {
this.setState({ error: true })
})
.then(() => {
console.log(`finish fetching ${i}`)
document.body.insertAdjacentHTML('beforeend', `<div>finish fetching ${i}</div>`)
})
}
this.finalExecution()
}
finalExecution = () => {
console.log('finish finalExecution')
document.body.insertAdjacentHTML('beforeend', `<div>finish finalExecution</div>`)
}
}
catA = new Cat()
catA.doit()
cart = [1, 2, 3]
class Cat {
constructor() {
this.setState = (param) => {
// console.log(param)
}
}
doit = () => {
const results = cart.map(async (i) => {
await axios.get(`https://jsonplaceholder.typicode.com/todos/${i}`)
.then(({ data }) => {
this.setState({ data })
})
.catch(() => {
this.setState({ error: true })
})
.then(() => {
console.log(`finish fetching ${i}`)
document.body.insertAdjacentHTML('beforeend', `<div>finish fetching ${i}</div>`)
})
})
Promise.all(results).finally(() => {
this.finalExecution();
})
}
finalExecution = () => {
console.log('finish finalExecution')
document.body.insertAdjacentHTML('beforeend', `<div>finish finalExecution</div>`)
}
}
catA = new Cat()
catA.doit()
Upvotes: 1
Reputation: 2825
You can use Promise.all
, this way you are sure that your requests are ok, something like:
doit = async () => {
const responses = await Promise.all(
cart.map(async (endpoint) => await axios.get('url'))
);
this.finalExecution(responses);
}
finalExecution = async (responses) => {
const [response1, response2] = await responses; // here you will have an array with resolved promises
this.setState(response1.data);
}
Upvotes: 0