【问题标题】:cloud functions onCall - how to return an object云函数 onCall - 如何返回一个对象
【发布时间】:2020-07-10 01:34:06
【问题描述】:

我正在尝试读取谷歌云函数 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 });

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2017-12-05
      • 1970-01-01
      相关资源
      最近更新 更多