【问题标题】:Cloud Function does not save to Firestore when deployed部署时 Cloud Function 不会保存到 Firestore
【发布时间】:2020-06-10 01:03:07
【问题描述】:

我已经部署了一个云函数,它加载一个 API 并将其内容保存到我的 Firestore 数据库中。当我使用 firebase 模拟器在本地环境中运行云功能时,它运行良好。但是,当我将相同的功能部署到 Google Cloud Platform 时,尽管它成功加载了 API,但它无法将内容保存到 Firestore。我的设置中还缺少什么?

这里是代码。我特意修改了 API 链接。

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

admin.initializeApp({
    credential: admin.credential.applicationDefault()
});

 exports.savePSEData = functions.https.onRequest((req, res) => {
    const url = <LINK REDACTED>;
    return new Promise((resolve, reject) => {

        axios
            .get(url)
            .then(response => {
                const date = response.data.as_of;
                for (var index in response.data.stock) {
                    var stock = response.data.stock[index]
                    createStockDocument(date, stock.symbol, stock.price.amount, stock.percent_change, stock.volume, callback => {
                        console.log(index)
                    })
                }
               return res.status(200).send("ok");
            })
            .catch(error => {
                console.log(error);
               return res.status(500).send(error);
            });
    })

});

function createStockDocument(date, symbol, amount, percentChange, volume, callback) {
    console.log("Creating temp package")
    const docRef = admin.firestore().doc(`${symbol}/${date}`);
    docRef.set({ 
        amount: amount,
        percent_change: percentChange,
        volume: volume
    })
    .then(docRef => {
        console.log('Document created')
        return callback(docRef)
    }).catch(error => {
        console.log(`Error trying to create document ${error}`)
        return callback(error);
    })

}

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您的代码忽略了docRef.set().then(...).catch(...) 返回的承诺。调用 thencatch 并不能完全处理承诺。 catch 只是返回另一个在整个链解析后异步解析的承诺。这意味着您的函数也在 Firestore 完成写入之前向客户端发送响应,这意味着它可能永远不会完成。 Functions are terminated immediately after the response is set.

    您应该让createStockDocument 从链中返回该承诺,然后让函数的调用者在发送响应之前等待它。最低限度:

    function createStockDocument(date, symbol, amount, percentChange, volume, callback) {
        console.log("Creating temp package")
        const docRef = admin.firestore().doc(`${symbol}/${date}`);
        return docRef.set(...).then(...)
    }
    

    我建议不要在这里使用 catch,而是让调用者 catcher 任何错误。

    createStockDocument(...)
    .then(() => res.status(200).send("ok"))
    .catch(error => res.status(500).send(error))
    

    我强烈建议牢牢掌握 Promise 的工作原理,因为它们对于在 Cloud Functions 中编写有效的代码至关重要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-17
      • 2020-04-29
      • 2019-10-25
      • 2018-05-06
      • 2020-12-16
      • 2023-03-13
      • 2018-03-19
      • 2019-09-21
      相关资源
      最近更新 更多