[英]How to scope Firebase in nested promise Cloud Functions
I am trying to set a few variables from Firebase and then pass those into a anotherfunction. 我正在尝试从Firebase设置一些变量,然后将它们传递给另一个函数。 Currently, the Promise.all is properly setting foo and bar, but an error is being thrown during the .then
, so the response isn't getting set in 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')
}
});
The error logged into the console is as follows: 登录到控制台的错误如下:
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)
How can return firebase.database().ref().update(updates);
如何return firebase.database().ref().update(updates);
be scoped to set the response from anotherFunction
? 可以设置来自anotherFunction
的响应?
You need to include the Firebase Admin SDK , typically called admin
. 您需要包括Firebase Admin SDK ,通常称为admin
。
As shown and explained in the getting started documentation for functions : 如功能入门文档中所示和说明:
Import the required modules and initialize 导入所需的模块并初始化
For this sample, your project must import the Cloud Functions and Admin SDK modules using Node require statements. 对于此样本,您的项目必须使用Node require语句导入Cloud Functions和Admin SDK模块。 Add lines like the following to your
index.js
file: 将以下内容添加到index.js
文件中:const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase);
These lines load the
firebase-functions
andfirebase-admin
modules, and initialize anadmin
app instance from which Realtime Database changes can be made. 这些行会加载firebase-functions
和firebase-admin
模块,并初始化一个admin
应用程序实例,可以从中更改实时数据库。
You then use it like this: 然后,您可以像这样使用它:
return admin.database().ref().update(updates);
Also see this complete example in the functions-samples
repo . 另请参见functions-samples
repo中的完整示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.