gpt4 book ai didi

reactjs - Axios 进入 .then 未按预期工作

转载 作者:行者123 更新时间:2023-12-04 01:44:30 27 4
gpt4 key购买 nike

我正在使用 axios 发出 http 请求。在 .then() 内部,我正在使用另一个 axios 调用。最后,我有第三个 then(),它应该在第二个 then 之后运行,但实际上并没有这样做。

let assets = [];

export const initAssets = () => {
return dispatch => {
dispatch(setLoadingToTrue());
axios.get('https://....json')
.then(response => {
for(let key in response.data) {
assets.push(response.data[key]);
}
})
.then(() => {
const token = '...';
assets.forEach((cur) => {
axios.get('...' + cur.ticker + '/quote?token=' + token)
.then(response => {
console.log(response);
cur.price = response.data.latestPrice;
})
})
})
.then(() => {
dispatch(initAllAssets(assets));
dispatch(setLoadingToFalse());
})
.catch(error => {
console.log(error);
dispatch(setLoadingToFalse());
})
}
}

在第二个 then 的 axios 请求完成之前,最后一个 .then 的调度正在执行。如何让最后一个 then 只在第二个 axios 请求完成后运行?

最佳答案

您可以使用 Promise.all 将响应返回到下一个 .then block ,一旦所有 promise 在第二个 .then 中解决,它将被调用

let assets = [];

export const initAssets = () => {
return dispatch => {
dispatch(setLoadingToTrue());
axios.get('https://....json')
.then(response => {
for(let key in response.data) {
assets.push(response.data[key]);
}
})
.then(() => {
const token = '...';
const promises = [];
assets.forEach((cur) => {
promises.push(axios.get('...' + cur.ticker + '/quote?token=' + token)
.then(response => {
console.log(response);
cur.price = response.data.latestPrice;
}))
})
return Promise.all(promises);
})
.then(() => {
dispatch(initAllAssets(assets));
dispatch(setLoadingToFalse());
})
.catch(error => {
console.log(error);
dispatch(setLoadingToFalse());
})
}
}

关于reactjs - Axios 进入 .then 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55882080/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com