javascript - 由于 promise 链,Firebase Firestore 更新查询未执行。我究竟做错了什么?

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

此代码在 firebase 云函数中执行,以在被添加到 firestore 的文档触发后进行 strip 充电。这只是问题所在的一个片段。该代码应该对卡进行收费,并在成功后,使用 newBalance 更新 firestore 中的“dexCoinBal”值。我通过获取以前的值然后随着更新一起移动来解决这个问题。但是,更新似乎根本没有运行。这可能与链接 promise 有关,但我无法弄清楚它到底是什么。如果有人能指出我做错了什么,那就太好了。我显然对 promises 理解不够。

 function charge (tok, amt, curr, uid) {
        const token = tok;
        const amount = amt;
        const currency = curr;
        const fStor = admin.firestore();

        stripe.charges.create({
            amount,
            currency,
            description: 'Example charge',
            source: token
        }).then(function(result){
            return fStor.collection('users').get();
        }).then(function(doc){
            if(doc.exists){
                const prev = doc.data().dexCoinBal;
                var numDexCoins = amt / (0.25 * 100);
                var newBal = numDexCoins + prev;

                //Update the number of dexcoins in database
                fStor.collection('users').doc(uid).update({
                    dexCoinBal: newBal
                });
            }
        });   
    }

完整代码如下。解决了这个问题。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const fStor = admin.firestore();
const settings = {timestampsInSnapshots: true};
fStor.settings = settings;

// TODO: Remember to set token using >> firebase functions:config:set stripe.token="SECRET_STRIPE_TOKEN_HERE"
const stripe = require('stripe')(functions.config().stripe.token);

function charge (tok, amt, curr, uid) {
    const token = tok;
    const amount = amt;
    const currency = curr;

    console.log("Outside");
    return stripe.charges.create({
        amount,
        currency,
        description: 'Example charge',
        source: token
    }).then(function(result){
        console.log("First Then");
        return fStor.collection('users').doc(uid).get();
    }).then(function(doc){
        console.log("Second Then");
        if(doc.exists){
            const prev = doc.data().dexCoinBal;
            var numDexCoins = amt / (0.25 * 100);
            var newBal = numDexCoins + prev;

            //Update the number of dexcoins in database
            fStor.collection('users').doc(uid).update({
                dexCoinBal: newBal
            });
        }
    });   
}

exports.createCharge = functions.firestore
    .document('charges/{chargeId}')
    .onCreate((snap, context) => {
      // Get an object representing the document
      // e.g. {'name': 'Marie', 'age': 66}
      const data = snap.data();

      // access a particular field as you would any JS property
      const token = data.token;
      const amount = data.amount;
      const currency = data.currency;
      const uid = data.uid;

    // perform desired operations ...
      return charge(token, amount, currency, uid);
    });

最佳答案

我在您的代码中看到两个问题:

1/通过执行 return fStor.collection('users').get(); 您将返回 QuerySnapshot 而不是 DocumentSnapshot。请参阅 get() 方法的文档 here .

文档说“QuerySnapshot 包含零个或多个表示查询结果的 DocumentSnapshot 对象。可以通过 作为数组访问文档docs 属性或使用 forEach 方法枚举。”

因此,当您在 then next then() 中执行 doc.data() 时,您很可能会遇到错误。

2/第二个问题,恕我直言,您没有在 charge 函数中返回任何东西。因为在 Cloud Function 中,您应该返回一个 promise (或在特定情况下返回一个值),所以您应该从您的函数中返回一个 promise 。您可能应该执行以下操作,但很难 100% 确定,因为您没有发布 Cloud Functions 的完整代码。

return stripe.charges.create({
       ....
    }).then(function(result){
        ....
    }).then(function(collection){
        ....
    });   

如果您添加完整的代码,我们可能会更准确地帮助您。


我还建议您观看来自 Firebase 团队的这两个必看视频,关于 Cloud Functions 和 promises:https://www.youtube.com/watch?v=7IkUgCLr5oAhttps://www.youtube.com/watch?v=652XeeKNHSk .

关于javascript - 由于 promise 链,Firebase Firestore 更新查询未执行。我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51577734/

相关文章:

javascript - jQuery:选择祖 parent 的 h1 标签

javascript - 预注册 Lambda 触发器 autoConfirmUser 不起作用

firebase - 与 firebase 实时数据库交互的dialogflow

javascript - 如何从重新定位的 float div 折叠空白区域?

javascript - "this"是如何在Javascript的回调中查找的

node.js - 使用 require() 并导入私有(private) npm 模块失败

node.js - "Path ' hashed_pa​​ssword ' is required"即使使用虚拟字段时 hash_password 字段已满

javascript - 如何从剧作家那里读取文本框值

android - firebase 函数中的 initializeApp() 问题

java - FirebaseRecyclerAdapter 强制我实现我不想要/不需要的方法