繁体   English   中英

云函数 onCall - 如何返回一个对象

[英]cloud functions onCall - how to return an object

我正在尝试读取谷歌云函数 onCall 函数的返回值,但我一直在读取 null。

这是我的角度代码:

const callable = this.angularFireFunctions.httpsCallable('createEvent');
callable(this.formGroup.value).toPromise()
.then((next) => {
  console.log(next); //function succeeds but returned null
})
.catch((err) => {
  console.log(err);
})

我定义了以下云函数。 一切都捆绑在一个事务中。

export const createEvent = functions.https.onCall((data: any, context: CallableContext) : any | Promise<any> =>
{
    const user_DocumentReference = db.collection('users').doc(context.auth?.uid);
    const event_DocumentReference = db.collection('events').doc();

    db.runTransaction((transaction: FirebaseFirestore.Transaction) =>
    {
        return transaction.getAll(user_DocumentReference)
        .then((documentSnapshots: FirebaseFirestore.DocumentSnapshot<any>[]) =>
        {
            const user_DocumentSnapshot = documentSnapshots[0].data();

            if (typeof user_DocumentSnapshot === 'undefined')
            {
                // return some error message json object
            }

            transaction.create(event_DocumentReference,
            {
                //json object
            });

            //return success object with few attributes
        })
        .catch((firebaseError: FirebaseError) =>
        {
            //return some error message json object
        }
    });
});

如何将 json 对象作为承诺返回? 我尝试了以下方法无济于事:

return Promise.resolve({ json object });
return Promise.reject({ json object });

您的顶级函数应该返回一个承诺,该承诺与要发送给客户端的数据一起解析。 从您的事务处理程序返回该值是不够的。 您还需要在顶级回报。 从这个开始:

return db.runTransaction(transaction => { ... })

正如您从 API 文档中看到的, runTransaction返回事务处理程序(或“updateFunction”)返回的承诺。

暂无
暂无

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

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