首页 > 解决方案 > 将元素推入数组仅在循环内有效

问题描述

我得到了一些我从 API 调用的数据,为此我正在使用 axios。当检索到数据时,我将其转储到一个名为“RefractorData()”的函数中,只是为了对其进行一点组织,然后将其推送到现有数组中。问题是,我的数组被填充在 forEach 中,我可以在那里 console.log 我的数据,但是一旦我退出循环,我的数组就是空的。

let matches: any = new Array();
const player = new Player();

    data.forEach(
          async (match: any) => {
            try {
              const result = await API.httpRequest(
                `https://APILink.com/matches/${match.id}`,
                false
              );
              if (!result) console.log("No match info");
              const refractored = player.RefractorMatch(result.data);
              matches.push({ match: refractored });
              console.log(matches);
            } catch (err) {
              throw err;
            }
          }
        );
        console.log(matches);

现在 forEach 中的第一个 console.log 正确显示数据,forEach 之后的第二个显示空数组。

标签: javascriptarraysnode.jstypescript

解决方案


设法用Promise.all()Array.prototype.map() 做到这一点。

const player = new Player();
const matches = result.data;

const promises = matches.map(async (match: any) => {
  const response: any = await API.httpRequest(
    `https://API/matches/${match.id}`,
    false
  );

  let data = response.data;
  return {
    data: player.RefractorMatch(data)
  };
});
const response: any = await Promise.all(promises);

推荐阅读