我正在尝试读取 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/