首页 > 解决方案 > 在先前调用的响应完成之前调用等待/异步 axios 调用

问题描述

我有一个 React 组件,它asynccomponentDidUpdate. 在该函数中,我有一组我调用的项目Promise.all。有一种情况axios是根据前一次调用返回的内容进行axios调用。我遇到的问题是axios在上一次调用的结果完成之前进行了axios调用,我不确定为什么会发生这种情况。

这是我的代码:

class Test extends Component {
  this.state = {
    experiments: []
  }
  async componentDidMount() {
    await this.getExperiments(); // function to fetch experiments from a db
  }
  async componentDidUpdate() {
    if (condition) {
      await myFunction()
    }
  }

  myFunction = async () => {
    try {
      const { experiments } = this.state;
      const results = await Promise.all(experiments.map(async experiment => {
        const firstAxiosCall = await axios.get(someUrl);
        const secondAxiosCall = await axios.get(anotherUrl)
        const { data } = secondAxiosCall; // THIS IS WHERE BUG OCCURS
        if (data.length === 0) {  // For one experiment, this is not empty, but it still goes into the if statement.
          await axios.post(thirdUrl)
        }
      }));
    } catch (e) {
      console.log('ERROR', e);
    }
  }
}

我知道这是一个错误,因为axios调用了 if 语句中的调用,并且我在后端收到一个 db 错误,说没有传入任何内容。我希望第二个 axios 调用中的数据在继续执行 if 语句之前首先返回。有什么我做错了吗?

我希望这是足够的信息!

谢谢你们!

标签: javascriptnode.jsreactjsapipromise

解决方案


我建议你使用这样的东西:

myFunction = async () => {
await axios.all([
    axios.get('http://someurl.com'),
    axios.get('http://anotherurl.com')
  ])
  .then(axios.spread((someUrlRest, anotherUrlRes) => {
    // do something with both responses
  });
}

推荐阅读