解析错误:Firebase 云函数中出现意外的令牌 selectWinner - Node.js V10

Posted

技术标签:

【中文标题】解析错误:Firebase 云函数中出现意外的令牌 selectWinner - Node.js V10【英文标题】:Parsing error: Unexpected token selectWinner in Firebase cloud function - Node.js V10 【发布时间】:2020-01-13 09:43:40 【问题描述】:

我无法部署我的云功能,因为我遇到了解析错误:Unexpected token selectWinner。

我已更新 .eslintrc.json 中的解析器选项以使用 ecmaVersion 2017,但这不起作用。进行更改后,我重新启动了我的文本编辑器(原子),但这也不起作用。

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
  

【问题讨论】:

This 可能是问题所在? 我使用的是节点 10,所以不确定我是否需要这样做?我刚刚更新了问题以包含我的 package.json 指定节点版本和我的 eslintrc.json 【参考方案1】:

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

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

你的意思是这个吗?

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

或者,更好的是,始终使用 async/await:

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);
);

【讨论】:

以上是关于解析错误:Firebase 云函数中出现意外的令牌 selectWinner - Node.js V10的主要内容,如果未能解决你的问题,请参考以下文章

如何修复节点中的“解析错误:意外的令牌 =>”?

eslint 解析错误:带有异步的意外令牌函数

模块解析失败:Webpack Typescript Loader 中出现意外的令牌

如何解决错误:Asp.Net 请求中出现意外的令牌“<”?

Webpack通过“模块解析失败,出现意外令牌”

如何解决“意外的令牌:预期的构造函数、方法、访问器或属性”错误?