[英]How to scope Firebase in nested promise Cloud Functions
我正在尝试从Firebase设置一些变量,然后将它们传递给另一个函数。 目前,Promise.all正确设置foo和酒吧,但过程中被抛出一个错误.then
,这样的反应是没有得到在火力地堡设置。
const functions = require('firebase-functions'),
admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.someFunc = functions.database.ref(`/data`).onWrite(event => {
const condition = event.data.val()
if (condition) {
// Get the data at this location only once, returns a promise, to ensure retrieval of foo and bar
const foo = event.data.adminRef.child('foo').once('value')
const bar = event.data.adminRef.child('bar').once('value')
return Promise.all([foo, bar]).then(results => {
const foo = results[0].val()
const bar = results[1].val()
return someModule.anotherFunction({
"foo": foo,
"bar": bar
}).then(response => {
// Get an error thrown that Firebase is not defined
let updates = {}
updates['/data'] = response
return firebase.database().ref().update(updates)
})
})
} else {
console.log('Fail')
}
});
登录到控制台的错误如下:
ReferenceError: firebase is not defined
at someModule.anotherFunction.then.response
(/user_code/index.js:100:16)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
如何return firebase.database().ref().update(updates);
可以设置来自anotherFunction
的响应?
您需要包括Firebase Admin SDK ,通常称为admin
。
如功能入门文档中所示和说明:
导入所需的模块并初始化
对于此样本,您的项目必须使用Node require语句导入Cloud Functions和Admin SDK模块。 将以下内容添加到
index.js
文件中:const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase);
这些行会加载
firebase-functions
和firebase-admin
模块,并初始化一个admin
应用程序实例,可以从中更改实时数据库。
然后,您可以像这样使用它:
return admin.database().ref().update(updates);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.