javascript - 云函数 onCall - 如何返回对象

标签 javascript angular firebase google-cloud-firestore google-cloud-functions

我正在尝试读取 Google Cloud Functions onCall 函数的返回值,但我一直读取 null。

这是我的 Angular 代码:

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 对象作为 promise ? 我尝试了以下方法,但没有成功:

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

最佳答案

您的顶级函数应该返回一个 promise ,该 promise 将解析发送给客户端的数据。从事务处理程序返回该值是不够的。您还需要获得最高级别的返回。从这个开始:

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

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

关于javascript - 云函数 onCall - 如何返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60917733/

相关文章:

javascript - ReactJs 如何呈现关联数组的对值

javascript - 更改所选文本的宽度

javascript - Angular - 无法获取父组件数据

angular - 如何在 NGRX 中使用来自另一个功能的选择器

firebase - 检查电子邮件是否已存在于 Flutter App 的 Firebase Auth 中

javascript - jQuery 查找整数并附加小数

javascript - 在 ng-select 中显示 map 值

javascript - 更改为使用自定义下拉列表后无法看到父变量?

ios - 需要 Firebase 重新验证

firebase - 如何在 Firebase 应用中获取 Cloud Storage 中所有文件的列表?