当前位置: 首页 > 知识库问答 >
问题:

分析错误:Firebase云函数-节点中出现意外的令牌selectWinner。JSV10

白子默
2023-03-14

我无法部署我的云函数,因为我被解析错误击中:意外的令牌selectWner。

我在中更新了解析器选项。eslintrc。json使用ECMAVersion2017,但这不起作用。在进行更改后,我重新启动了文本编辑器(atom),但这也不起作用。

exports.updatePollWinner = functions.firestore.document('updatePollWinner/{id}').onCreate(trigger => {
  const week = trigger.get('week');
  return db.collection("polls").where("sport", "==", 1).where("week", "==", week).where("pollType", "==", "WDIS").get()
  .then((querySnapshot) => {
    await selectWinner(querySnapshot)
  });

});

async function selectWinner(querySnapshot) {
  const scoringTags = ["STD", "0.25PPR", "0.5PPR", "PPR", "0.10PPC", "0.25PPC", "0.5PPC", "4PTPASS", "5PTPASS", "6PTPASS", "-2INT", "TEPREMIUM"];
  let winningChoiceIds = [];
  let totalPollIds = [];
  for (const doc of querySnapshot) {
    await processWinner(doc)
  }
  admin.firestore().doc('triggerAccuracyCalculation/'+Date.now().toString()).set({
    winningChoiceIds: winningChoiceIds,
    totalPollIds: totalPollIds,
    week: week
  });
}

async function processWinner(doc) {
  totalPollIds.push(doc.id);
  let pollData = doc.data();
  let tags = pollData.tags.filter(tag => scoringTags.includes(tag.code)).map(tag => tag.code);
  let winner = {score: 0, choice: {}, choiceId: null};
  for (const choice of pollData.choices) {
    await processChoice(choice)
  }
  winningChoiceIds.push(winner.choiceId);
  const pollDoc = db.doc(`polls/${doc.id}`);
  pollDoc.update({winner: winner});
}

async function processChoice(choice) {
    let choiceId = choice.id
    let mappedChoices = choice.players.map(player => {
      return { displayName: player.displayName, playerId: player.playerId, position: player.position, team: player.team }
    });

    // ToDo: What happens if someone posts a poll with two players in one option? This poll should be ignoree from accuracy calculation
    // ignmore if option has more than one player
    // if (mappedChoices.length > 1) return;

    const player = mappedChoices[0]

    // We can't score defense
    if (player.position === "DEF") {
      return;
    }

    const playerId = player.playerId;
    // Make FFN API call to retrieve stats for that player in that weekconst statsEndpoint = `https://www.fantasyfootballnerd.com/service/player/json/${functions.config().ffnerd.key}${req.url}`;

    const statsEndpoint = `https://www.fantasyfootballnerd.com/service/player/json/${functions.config().ffnerd.key}/${playerId}`;
    const json = {"Stats": {"2019": ""}, "Player": {}};
    https.get(statsEndpoint, (resp) => {
      let data = '';

      resp.on('data', (chunk) => {
        data += chunk;
      });

      resp.on('end', () => {
        const weekString = week.toString();
        const fetchedStats = JSON.parse(data).Stats
        if (!fetchedStats) return;
        const response = fetchedStats["2019"]
        if (!response) return;
        // TODO SCORE KICKERS AND DEFENSES
        const stats = response[weekString];
        let score = 0;

        // Additional bonus for TE premium leagues
        if (player.position === "TE" && tags.includes("TEPREMIUM")) {
          stats["receptions"] ? score += parseInt(stats["receptions"]) / 2 : false
        }

        // Do stuff no matter what your position is
        stats["recYards"] ? score += parseInt(stats["recYards"]) / 10 : false
        stats["recTD"] ? score += parseInt(stats["recTD"]) * 6 : false
        stats["rushYards"] ? score += parseInt(stats["rushYards"]) / 10 : false
        stats["rushTD"] ? score += parseInt(stats["rushTD"]) * 6 : false
        stats["xpMade"] ? score += parseInt(stats["xpMade"]) : false
        stats["fgMade"] ? score += parseInt(stats["fgMade"]) * 3 : false
        stats["kickoffRet"] ? score += parseInt(stats["kickoffRet"]) / 10 : false
        stats["SackYards"] ? score -= parseInt(stats["SackYards"]) / 10 : false
        stats["fumbleLost"] ? score -= parseInt(stats["fumbleLost"]) * 2 : false

        // Determine winner
        // ToDo: handle ties
        if (score > winner.score) {
          winner.score = score;
          winner.choiceId = choiceId;
          winner.choice = choice;
        }
      });
    }).on("error", (err) => {
      console.log("Error: ", err.message);
    });
}

这些函数应该同步处理,但是由于这个错误,我甚至不能得到第一个被调用的函数。

package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "10"
  },
  "dependencies": {
    "express": "^4.17.1",
    "firebase-admin": "~8.0.0",
    "firebase-functions": "^3.0.0",
    "google-gax": "^1.1.1",
    "install": "^0.12.2",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.26",
    "node-fetch": "^2.6.0",
    "npm": "^6.10.2",
    "twilio": "^3.30.3",
    "xml2js": "^0.4.19"
  },
  "devDependencies": {
    "eslint": "^6.3.0",
    "eslint-plugin-promise": "^4.2.1",
    "firebase-functions-test": "^0.1.6"
  },
  "private": true
}

eslintrc.json

{
  "parserOptions": {
    // Required for certain syntax usages
    "ecmaVersion": 2017
  },
  "plugins": [
    "promise"
  ],
  "extends": "eslint:recommended",
  "rules": {
    // Removed rule "disallow the use of console" from recommended eslint rules
    "no-console": "off",

    // Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules
    "no-regex-spaces": "off",

    // Removed rule "disallow the use of debugger" from recommended eslint rules
    "no-debugger": "off",

    // Removed rule "disallow unused variables" from recommended eslint rules
    "no-unused-vars": "off",

    // Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules
    "no-mixed-spaces-and-tabs": "off",

    // Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules
    "no-undef": "off",

    // Warn against template literal placeholder syntax in regular strings
    "no-template-curly-in-string": 1,

    // Warn if return statements do not either always or never specify values
    "consistent-return": 1,

    // Warn if no return statements in callbacks of array methods
    "array-callback-return": 1,

    // Require the use of === and !==
    "eqeqeq": 2,

    // Disallow the use of alert, confirm, and prompt
    "no-alert": 2,

    // Disallow the use of arguments.caller or arguments.callee
    "no-caller": 2,

    // Disallow null comparisons without type-checking operators
    "no-eq-null": 2,

    // Disallow the use of eval()
    "no-eval": 2,

    // Warn against extending native types
    "no-extend-native": 1,

    // Warn against unnecessary calls to .bind()
    "no-extra-bind": 1,

    // Warn against unnecessary labels
    "no-extra-label": 1,

    // Disallow leading or trailing decimal points in numeric literals
    "no-floating-decimal": 2,

    // Warn against shorthand type conversions
    "no-implicit-coercion": 1,

    // Warn against function declarations and expressions inside loop statements
    "no-loop-func": 1,

    // Disallow new operators with the Function object
    "no-new-func": 2,

    // Warn against new operators with the String, Number, and Boolean objects
    "no-new-wrappers": 1,

    // Disallow throwing literals as exceptions
    "no-throw-literal": 2,

    // Require using Error objects as Promise rejection reasons
    "prefer-promise-reject-errors": 2,

    // Enforce “for” loop update clause moving the counter in the right direction
    "for-direction": 2,

    // Enforce return statements in getters
    "getter-return": 2,

    // Disallow await inside of loops
    "no-await-in-loop": 2,

    // Disallow comparing against -0
    "no-compare-neg-zero": 2,

    // Warn against catch clause parameters from shadowing variables in the outer scope
    "no-catch-shadow": 1,

    // Disallow identifiers from shadowing restricted names
    "no-shadow-restricted-names": 2,

    // Enforce return statements in callbacks of array methods
    "callback-return": 2,

    // Require error handling in callbacks
    "handle-callback-err": 2,

    // Warn against string concatenation with __dirname and __filename
    "no-path-concat": 1,

    // Prefer using arrow functions for callbacks
    "prefer-arrow-callback": 1,

    // Return inside each then() to create readable and reusable Promise chains.
    // Forces developers to return console logs and http calls in promises.
    "promise/always-return": 2,

    //Enforces the use of catch() on un-returned promises
    "promise/catch-or-return": 2,

    // Warn against nested then() or catch() statements
    "promise/no-nesting": 1
  }
}

共有1个答案

乐寒
2023-03-14

您正在未标记为async的函数中使用wait。那是无效的。

.then((querySnapshot) => {
  await selectWinner(querySnapshot)
});

你是说这个吗?

.then((querySnapshot) => {
  return selectWinner(querySnapshot)
});

或者,更好的是,一致地使用async/wait:

exports.updatePollWinner =
functions.firestore.document('updatePollWinner/{id}').onCreate(async (trigger) => {
  const week = trigger.get('week');
  const querySnapshot = await db.collection("polls").where("sport", "==", 1).where("week", "==", week).where("pollType", "==", "WDIS").get()
  await selectWinner(querySnapshot);
});
 类似资料:
  • 应用程序。js公司 在执行上述代码时,我得到以下错误。 当我将鼠标悬停在线上方时,会出现这个错误 在我的VS代码中。 当我使用node运行代码时,即在上。我在终端中收到以下错误: 我做错了什么?我希望最后的obj的值是{1:,2:,3:}

  • 问题内容: 我不明白怎么了。我在其他论坛上讨论了翻译和通天塔。我需要做什么? 我的代码: 和错误 问题答案: ES6导入是最近引入的功能,并且Node的当前稳定版本尚不支持它们。Node.js问题跟踪器对此存在一个未解决的问题 -但在V8和Node添加对此功能的支持之前,您将需要使用编译器(最受欢迎的是babel)才能使用导入。 为了快速尝试转译,babel提供了基于Web的REPL。这段演示了您

  • 问题内容: 我在解析简单的JSON字符串时遇到问题。我已经在JSONLint上检查了它们,它表明它们是有效的。但是当我尝试使用jQuery替代方法解析它们时,出现了以下错误: 注意:我正在使用PHP 对字符串进行编码。 问题答案: 您的数据已经是一个对象。无需解析。javascript解释器已经为您解析了它。

  • 基本上,我正在youtube上做注册和登录教程。它使用的是旧版本的PHP,我试图更新代码,但出现以下错误: 分析错误:语法错误,在第23行的C:\Program Files(x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\Forum\Forum\core\functions\users.php中出现意外“,” users.php

  • 我正在尝试使用节点版本6.2.1与我的一些代码。计划将大多数面向超回调的代码迁移到看起来更干净、性能更好的代码。 我不知道为什么,当我试图执行节点代码时,终端抛出了一个错误。 你好。js 日志- 我错过了什么?请给我一些同样的灯。 更新1: 我试着按照昆汀的建议使用巴贝尔,但是,我仍然得到以下错误。 更新代码- 日志-

  • 问题内容: 我尝试了以下简单的JavaScript代码: 例如,在Chrome控制台中,这将返回 SyntaxError:意外令牌: 我在JSONLint上尝试了JSON ,它是有效的。 您看到错误了吗? 问题答案: FWIW,改为使用。比。