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的每次迭代运行后发送。
它有点原始但我们走了:
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()
}
});
})
});
};
你可以map
最后的承诺成阵列,然后dispatch
在Promise.all
。
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
})
);
});
};