javascript - 在先前调用的响应完成之前调用等待/异步 axios 调用
问题描述
我有一个 React 组件,它async
在componentDidUpdate
. 在该函数中,我有一组我调用的项目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 语句之前首先返回。有什么我做错了吗?
我希望这是足够的信息!
谢谢你们!
解决方案
我建议你使用这样的东西:
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
});
}
推荐阅读
- google-cloud-platform - 无法在 GCP 上启用 API(用户角色=所有者 && 结算帐户已关联)
- python - 如何将heroku中的django应用程序连接到mongodb atlas?
- powershell - 以与证书导入向导相同的方式添加证书 [Powershell]
- microsoft-graph-api - 无法在asp.net web api项目中获取刷新令牌,使用microsoft graph api
- ansible - awx-manage inventory_import --inventory-name --overwrite 不起作用
- java - Java 的只有一个消费者和生产者线程的并发队列
- python - python脚本在后台运行时网站上的Flask Progressbar
- ios - 在swift 5中从UIImage中删除白色背景
- python - 如何使用 cx_oracle 从 blob 列数据中检索数据?
- django - Django AbstractUser 密码没有散列