Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在map函数中中断循环并移动_Javascript_Node.js - Fatal编程技术网

Javascript 在map函数中中断循环并移动

Javascript 在map函数中中断循环并移动,javascript,node.js,Javascript,Node.js,所以基本上我在我的应用程序中做一个cron作业,每3小时启动一次,并通过调用RiotApi更新用户的分数 基本上是目前为止的功能 exports.updatePlayersPoints = async () => { console.log('STARTED UPDATING'); try { const players = await UserLadder.findAll(); await Promise.all( players.map(async

所以基本上我在我的应用程序中做一个cron作业,每3小时启动一次,并通过调用RiotApi更新用户的分数

基本上是目前为止的功能

exports.updatePlayersPoints = async () => {
  console.log('STARTED UPDATING');
  try {
    const players = await UserLadder.findAll();

    await Promise.all(
      players.map(async (player) => {
        const p = await RiotAccount.findOne({
          where: {
            userId: player.userId,
          },
          include: RiotRegions,
        });

        const beginTime = new Date(player.dataValues.createdAt);

        let data;

        try {
          const res = await axios.get(
            `https://${
              p.dataValues.riot_region.dataValues.name
            }.api.riotgames.com/lol/match/v4/matchlists/by-account/${
              p.dataValues.accountId
            }?queue=420&beginTime=${beginTime.getTime()}&api_key=${
              process.env.RIOT_KEY
            }`
          );

          data = res.data;
        } catch (error) {
          if (!error.response.status === 404) {
            console.error(error);
          }
        }

        if (!data) {
          return;
        }

        let totalScore = player.dataValues.userPoints;

        await Promise.all(
          data.matches.map(async (match, i) => {
            if (i < 15) {
              const { data } = await axios.get(
                `https://${p.dataValues.riot_region.dataValues.name}.api.riotgames.com/lol/match/v4/matches/${match.gameId}?api_key=${process.env.RIOT_KEY}`
              );

              const calculateScore = () => {
                return new Promise((resolve) => {
                  const { stats } = _.find(
                    data.participants,
                    (o) => o.championId === match.champion
                  );

                  const killsPts = stats.kills * 2;
                  const deathPts = stats.deaths * -1.5;
                  const assistsPts = stats.assists;
                  const wardsPts = stats.wardsPlaced / 4;
                  const firstBloodPts = stats.firstBloodKill ? 3 : 0;
                  const firstBloodAssistPts = stats.firstBloodAssist ? 3 : 0;
                  const firstTowerPts = stats.firstTowerKill ? 2 : 0;
                  const firstTowerAssistPts = stats.firstTowerAssist ? 2 : 0;

                  const score =
                    killsPts +
                    deathPts +
                    assistsPts +
                    wardsPts +
                    firstBloodPts +
                    firstBloodAssistPts +
                    firstTowerPts +
                    firstTowerAssistPts;

                  totalScore += score;

                  resolve();
                });
              };

              await calculateScore();
            }
          })
        );

        const user = await UserLadder.findOne({
          where: {
            userId: player.userId,
          },
        });

        user.userPoints = parseFloat(totalScore);
        user.lastGameId = data.matches[0].gameId;

        await user.save();
      })
    );
    console.log('FINISHED UPDATING');
  } catch (error) {
    console.error(error);
  }
};
但是现在,在我的第二个映射比赛的映射函数中,我没有这样做,因此,如果数据库中的最后一个比赛与当前映射的比赛id匹配,我希望停止映射函数,而不是继续此记录或之后的记录,因为这也意味着它们都已被计数

但我似乎找不到一个办法来做这件事

我试着使用break但它不起作用

有什么想法吗

使用for循环

我用for循环做了一个小测试,所以我试了一下

    for (let i = 0; i < 15; i++) {
      await new Promise(async (resolve, reject) => {
        const match = data.matches[i];
        console.log(match);
        resolve();
        if (i === 1) {
          break;
        }
      });
    }
for(设i=0;i<15;i++){
等待新承诺(异步(解析、拒绝)=>{
常量匹配=数据。匹配[i];
控制台日志(匹配);
解决();
如果(i==1){
打破
}
});
}
但我还是犯了同样的错误

SyntaxError:非法中断语句

在执行映射之前,您应该过滤要处理的匹配项,而不是试图“破坏”映射

大概是这样的:

await Promise.all(
  const filteredMatches = data.matches.filter(match => match.gameId > previousId);
  filteredMatches.map(async (match, i) => { ...
更多关于

编辑:如果生成的id是随机的,并且没有顺序,您可以将以前的所有id存储在一个集合中,然后只需询问它以前是否添加过

await Promise.all(
      const filteredMatches = data.matches.filter(match => mySet.has(match.gameId));
      filteredMatches.map(async (match, i) => { ...

更多信息。

当我在谷歌上搜索“javascript破坏映射函数”时,我遇到了这个问题。这是否适用于您的用例@杰米:我看到了,我试过了,但出现了一个“非法中断”错误,我会用code@Jamine刚刚更新了它,lmk如果它有帮助的话我考虑过这样做,但问题是返回的ID实际上是随机的,所以match.gameId>以前不起作用,我需要做的是完全停止它,当它击中之前,所以它不会继续它或任何事情之后。很抱歉反应太晚。:)我意识到可能有必要添加一个!喜欢has(match.gameId)为了只过滤那些我们以前没有处理过的内容,它采用了相反的方法。
await Promise.all(
      const filteredMatches = data.matches.filter(match => mySet.has(match.gameId));
      filteredMatches.map(async (match, i) => { ...