簡體   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