循环遍历数组后如何发送?

问题描述 投票:0回答:2
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的每次迭代运行后发送。

arrays reactjs redux dispatch
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()
            }
          });
      })
    });
};

0
投票

你可以map最后的承诺成阵列,然后dispatchPromise.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
        })
      );
    });
};
© www.soinside.com 2019 - 2024. All rights reserved.