如何在异步循环执行完成后才执行某些语句

时间:2021-03-09 20:07:51

标签: javascript reactjs

如何仅在 forEach 函数内的所有 Async 调用执行后才运行函数 FinalExecution?

  doit=()=>{
          cart.forEach(async(i)=>{
              
              await axios.get(`localhost.........`})
              .then(({data})=>{
                   this.setState({data})})
              .catch(()=>{
                    this.setState({error:true})});
           })
           this.finalExecution();
        }
     
  finalExecution=()=>{
       .......
       .......
  }

2 个答案:

答案 0 :(得分:1)

使用 for loopPromise.all()

for 循环:

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

答案 1 :(得分:0)

您可以使用 Promise.all,这样您就可以确定您的请求是正确的,例如:

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);
}