javascript优化.map以传播运算符

时间:2019-03-04 12:36:04

标签: javascript

如果有odata nextlink,我正在使用递归函数进行异步调用。通过使用地图将项目推入teamsArray,它可以正常工作。问题悬停是我正在遍历每个项目,而不是将对象合并在一起。我尝试使用以下内容,但无济于事:

teamsArray = {}
    teamsArray = { ...teamsArray, ...latstestResults}

当前有效但未优化的代码:

export const fetchAllTeams = () => {
    return dispatch => {
        dispatch(fetchAllTeamsRequest());
    };
};

export const fetchAllTeamsRequest = () => {
    return dispatch => {
        dispatch(getAllTeamStarted());

        let teamsArray = [];
        getAllTeams("", teamsArray, dispatch);
    };
};

const getAllTeams = (url, teamsArray, dispatch) => {
    if (url === "") {
        url = "https://graph.microsoft.com/v1.0/me/memberOf?$top=10";
    }

    const getTeams = adalGraphFetch(fetch, url, {})
        .then(response => {
            if (response.status != 200 && response.status != 204) {
                dispatch(fetchAllTeamsFailure("fout"));
                return;
            }
            response.json().then(result => {
                if (result["@odata.nextLink"]) {
                    const teams = objectToArray(result.value);
                    teams.map(team => {
                        teamsArray.push(team);
                    });
                    getAllTeams(result["@odata.nextLink"], teamsArray, dispatch);
                } else {
                    const latestResult = objectToArray(result.value);
                    latestResult.map(team => {
                        teamsArray.push(team);
                    });
                    console.log("the teams", teamsArray);
                    dispatch(fetchAllTeamsSucces(result));
                }
            });
        })
        .catch(error => {
            dispatch(fetchAllTeamsFailure(error));
        });
};

1 个答案:

答案 0 :(得分:0)

类似的事情可能对您有用。

我将分页的提取重构为一个async函数,如果有更多的项目需要提取,则该函数会自行调用,然后最终以全部结果解析。

采用干式编码,因此可能存在错误和YMMV,但希望对您有所帮助。

export const fetchAllTeams = () => {
  return dispatch => {
    dispatch(fetchAllTeamsRequest());
  };
};

export const fetchAllTeamsRequest = () => {
  return async dispatch => {
    dispatch(getAllTeamStarted());
    try {
      const teamsArray = await getPaged(
        "https://graph.microsoft.com/v1.0/me/memberOf?$top=10",
      );
      dispatch(fetchAllTeamsSucces(teamsArray));
    } catch (err) {
      dispatch(fetchAllTeamsFailure(err));
    }
  };
};

const getPaged = async (url, resultArray = []) => {
  const response = await adalGraphFetch(fetch, url, {});
  if (response.status != 200 && response.status != 204) {
    throw new Error("failed to fetch teams");
  }
  const result = await response.json();
  objectToArray(result.value).forEach(team => resultArray.push(team));
  if (result["@odata.nextLink"]) {
    // Get more items...
    return getPaged(resultArray, result["@odata.nextLink"]);
  }
  return resultArray; // All done, return the teams array.
};