繁体   English   中英

发布订阅云功能 - 异步等待

[英]Pub Sub Cloud Function - Async Await

尝试通过预定的 Firebase 函数完成以下操作:

  1. 获取 Firestore 集合
  2. 删除收藏
  3. 向外部 API 发出 Get 请求
  4. 将获取请求结果写入 Firestore 集合。

该功能无法部署。 错误日志只说{"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code.

当我在本地运行模拟器套件时,我没有收到任何错误,但数据库没有更新。

我在附加到“onRun”方法的“=>”上遇到了linting错误。 不确定这是 Firebase 函数中 ES6 的代码问题还是 ESLint 问题。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');

admin.initializeApp();
const db = admin.firestore();

exports.scheduledFunction = functions.pubsub
    .schedule("every 2 minutes")
    .timeZone("America/New_York")
    .onRun(async (context) => {

      try {

        const querySnapshot = await db.collection("my_collection").get();
        console.log(querySnapshot.docs)
        const promises = querySnapshot.docs.map(doc => db.collection("my_collection").doc(doc.id).delete());

        await Promise.all(promises);

        const options = {
          "method": "get",
          "url": "www.myUrl.com",
          "headers": {
            "Cookie": "...",
          },
        };

        const axiosResponse = await axios(options);
        const apiResponse = JSON.parse(axiosResponse.data);
        const parsedResponse = apiResponse["news_results"];

        const docCreationPromises = parsedResponse.map(response => db.collection("my_collection").add(parsedResponse))

        await Promise.all(docCreationPromises);

        return null;

      } catch (error) {
        console.log(error);
        return null;
      }

    });

对于=>的 ESLint 问题,请尝试在 ESLint 配置ecmaVersion设置为 8。

module.exports = {
  root: true,
  env: {
    es6: true,
    node: true,
  },
  extends: [
    "eslint:recommended",
    "google",
  ],
  parserOptions: {
    ecmaVersion: 8
  }
};

当我在本地运行模拟器套件时,我没有收到任何错误,但数据库没有更新。

您使用的是 Firestore 模拟器吗? 如果是,则数据将添加到那里而不是在生产中,因此您只能在模拟器中看到数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM