This question already has answers here:
Function returned undefined, expected Promise or value
                                
                                    (3个答案)
                                
                        
                在10个月前关闭。
            
        

我正在尝试使用以下函数来计算集合中文档的总数:https://stackoverflow.com/a/49407570/8312532,但是我看到firebase函数已更新:https://firebase.google.com/docs/functions/beta-v1-diff#cloud-firestore

因此,我正在尝试:

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

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

exports.documentWriteListener =
functions.firestore.document('domiciliarios/{uid}')
.onWrite((change, context) => {

        if (!change.before) {
                // New document Created : add one to count
                db.doc(docRef).get().then(snap => {
                        db.doc(docRef).update({numberOfDocs: snap.numberOfDocs + 1});
                        return;
                });

        } else if (change.before && change.after) {
                // Updating existing document : Do nothing
                return;

        } else if (!change.after) {
                // Deleting document : subtract one from count
                db.doc(docRef).get().then(snap => {
                    db.doc(docRef).update({numberOfDocs: snap.numberOfDocs - 1});
                    return;
                });
        }

    });


但是,当我在Firestore中添加新文档时,出现以下错误:

Function returned undefined, expected Promise or value


任何的想法?

最佳答案

当所有异步工作完成时,Firestore触发器应返回一个promise解析的承诺,如果没有工作,则返回null。您的三种情况中的每一种都需要具有适当的返回值。

    if (!change.before) {
        // New document Created : add one to count
        return db.doc(docRef).get().then(snap => {
            return db.doc(docRef).update({numberOfDocs: snap.numberOfDocs + 1});
        });
    } else if (change.before && change.after) {
        // Updating existing document : Do nothing
        return null;
    } else if (!change.after) {
        // Deleting document : subtract one from count
        return db.doc(docRef).get().then(snap => {
            return db.doc(docRef).update({numberOfDocs: snap.numberOfDocs - 1});
        });
    }


如果您要花时间使用Cloud Functions,那么您绝对应该学习promise如何工作。从此处开始的视频教程分为三部分:https://www.youtube.com/watch?v=7IkUgCLr5oA&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=1

09-26 02:37
查看更多