user15334991
user15334991

Reputation:

how to execute certain statement only after the Async loop execution is completed

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

Answers (2)

yihsiu
yihsiu

Reputation: 88

Use for loop or Promise.all()

for loop:

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()

Promise.all()

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

AdriSolid
AdriSolid

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

Related Questions