Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.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 分析错误:Firebase云函数中出现意外的令牌selectWinner-Node.js V10_Javascript_Node.js_Firebase_Google Cloud Functions - Fatal编程技术网

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

Javascript 分析错误:Firebase云函数中出现意外的令牌selectWinner-Node.js V10,javascript,node.js,firebase,google-cloud-functions,Javascript,Node.js,Firebase,Google Cloud Functions,我无法部署我的云函数,因为我遇到了一个解析错误:意外的令牌selectWinner 我已经更新了.eslintrc.json中的解析器选项,以使用ecmaVersion 2017,但这不起作用。在进行更改后,我重新启动了文本编辑器atom,但也没有起作用 exports.updatePollWinner = functions.firestore.document('updatePollWinner/{id}').onCreate(trigger => { const week = t

我无法部署我的云函数,因为我遇到了一个解析错误:意外的令牌selectWinner

我已经更新了.eslintrc.json中的解析器选项,以使用ecmaVersion 2017,但这不起作用。在进行更改后,我重新启动了文本编辑器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
  }
}
您正在未标记为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);
});

可能是问题吗?我正在使用节点10,所以不确定是否需要执行这些操作?我刚刚更新了这个问题,将指定节点版本的package.json和eslintrc.json包含在内