0
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 的每次迭代运行后调度。

4

2 回答 2

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()
            }
          });
      })
    });
};
于 2019-01-31T00:43:59.850 回答
0

您可以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
        })
      );
    });
};
于 2019-01-31T00:45:13.837 回答