gpt4 book ai didi

javascript - 如何在嵌套 Promise Cloud Functions 中确定 Firebase 的范围

转载 作者:行者123 更新时间:2023-12-01 03:40:09 25 4
gpt4 key购买 nike

我正在尝试从 Firebase 设置一些变量,然后将它们传递给另一个函数。目前,Promise.all 已正确设置 foo 和 bar,但在 .then 期间抛出错误,因此未在 Firebase 中设置响应。

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的响应?

最佳答案

您需要include the Firebase Admin SDK ,通常称为admin

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. Add lines like the following to your index.js file:

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

These lines load the firebase-functions and firebase-admin modules, and initialize an admin app instance from which Realtime Database changes can be made.

然后你可以像这样使用它:

return admin.database().ref().update(updates);

另请参阅此 complete example in the functions-samples repo .

关于javascript - 如何在嵌套 Promise Cloud Functions 中确定 Firebase 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43960390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com