我有一个 React Redux 应用,它需要使用 axios
调用多个 API 端点,等待这些 API 调用的结果,然后分派(dispatch)一个操作。
问题:在我当前的下面实现中,在 axios< 返回 API 调用结果之前,
.redux-thunk
似乎正在调度操作
我们如何解决这个问题,以便在分派(dispatch)操作之前等待 3 个 axios
调用返回所有 3 个结果?
/src/actions/index.js
const axios = require('axios');
import { GET_PRICES } from './types';
export function getSpotPrice(crypto) {
axios.get(`https://api.coinbase.com/v2/prices/${crypto}-USD/spot`).then( (response) => {
return parseFloat(response.data.data.amount);
}).catch((err) => {
console.log(err)
})
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export function getSpotPrices() {
return function(dispatch) {
const cryptoList = ['BTC', 'ETH', 'XRP'];
let cryptoRates = {}
cryptoList.forEach(async (crypto, i) => {
await timeout(1000); // Wait 1 sec between API calls
cryptoRates[crypto] = await getSpotPrice(crypto);
});
dispatch({
type: GET_PRICES,
payload: cryptoRates,
})
console.log('cryptoRates:', cryptoRates) // returns {}
}
}
最佳答案
在分派(dispatch)之前,您需要让包含函数异步等待所有异步调用,如下所示:
export function getSpotPrices() {
return async function(dispatch) {
const cryptoList = ['BTC', 'ETH', 'XRP'];
let cryptoRates = {}
for(let crypto of cryptoList) {
await timeout(1000); // Wait 1 sec between API calls
cryptoRates[crypto] = await getSpotPrice(crypto);
}
dispatch({
type: GET_PRICES,
payload: cryptoRates,
});
console.log('cryptoRates:', cryptoRates);
}
}
关于javascript - 在 React Redux 中调度操作之前等待多个 Axios 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57633469/