import { FETCH_DATA } from "./types";
export const fetchData = () => dispatch => {
const array = [];
fetch(
"https://example-api-endpoint.com"
)
.then(res => res.json())
.then(data =>
data.forEach(element => {
fetch(
"https://another-example-api-endpoint.com"
)
.then(res => res.json())
.then(data => {
array.push(data);
dispatch({
type: FETCH_DATA,
payload: array
});
});
})
);
};
当前,我正在分派每个元素。我想知道是否有一种方法可以在forEach的每次迭代运行后分配。
答案 0 :(得分:0)
这有点原始,但是我们开始:
import { FETCH_DATA } from "./types";
export const fetchData = () => dispatch => {
const array = [];
var dispatchData = () => {
dispatch({
type: FETCH_DATA,
payload: array
});
}
fetch(
"https://example-api-endpoint.com"
)
.then(res => res.json())
.then(data =>{
var fetchCount = 0
data.forEach((element,index) => {
fetch(
"https://another-example-api-endpoint.com"
)
.then(res => res.json())
.then(data => {
array.push(data);
fetchCount++;
if(fetchCount === data.length){
dispatchData()
}
});
})
});
};
答案 1 :(得分:0)
您可以将最终的承诺map
Promise.all
放入数组,然后dispatch
放入https://docs.oracle.com/javase/10/docs/api/java/util/Optional.html。
import { FETCH_DATA } from "./types";
export const fetchData = () => dispatch => {
fetch("https://example-api-endpoint.com")
.then(res => res.json())
.then(data => {
const promises = data.map(element =>
fetch("https://another-example-api-endpoint.com").then(res =>
res.json()
)
);
Promise.all(promises).then(payload =>
dispatch({
type: FETCH_DATA,
payload
})
);
});
};