正如我的问题标题所述,我希望在全局范围内将一个防火墙查询结果加载到一个变量中,以供以后使用。
我希望稍后在动态侦听器中使用该值,并且我不想一次又一次地重新查询它。
我试着向谷歌寻求一个简单的解决方案。我已经尝试过用允诺、回调和异步等待来实现我自己的解决方案,但是没有结果。
这来自github文档,该文档展示了如何做我想做的事情,但不需要查询。
https://github.com/GoogleCloudPlatform/nodejs-docs-samples/blob/master/functions/tips/index.js
const heavyComputation = () => {
// Multiplication is more computationally expensive than addition
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
return numbers.reduce((t, x) => t * x);
};
const functionSpecificComputation = heavyComputation;
const fileWideComputation = lightComputation;
// [START functions_tips_scopes]
// [START run_tips_global_scope]
// Global (instance-wide) scope
// This computation runs at instance cold-start
const instanceVar = heavyComputation();这是我自己的尝试
const getNBAScoreKey = () => {
return new Promise(resolve => {
scoresRef.onSnapshot(nbaScoreKeySnapshot => {
console.log("the value inside the score key: " + nbaScoreKeySnapshot.data()["FantScores"]);
resolve(nbaScoreKeySnapshot.data());
});
});
}我希望变量是一个具有数据的对象,但是不管我尝试什么实现,我都会得到“未定义的”。
发布于 2019-08-30 23:45:25
您可以在全局范围内设置变量并在scoresRef.onSnapshot中重新分配它的值,但是如果您试图立即访问该值,而不等待从数据库中获取数据,那么当然,由于数据尚未被取走,您将得到未定义的值。
因此,在您的情况下,您必须使用可观察的设计模式,使用像rxjs这样的库,或者自己实现它,
可观察性允许您定义变量并订阅值更改事件。
简单观测器实现
let observer = {
value: {} ,
subscribers: [] ,
subscribe: function (cb ) { this.subscribers.push(cb)} ,
notify: function (data) { this.value = data ; this.subscribers.forEach( s => s(data);}
} 若要订阅值更改,必须调用observer.subscribe并传递回调函数,以便在数据更改时触发
observer.subscribe((data)=> { console.log('first', data ) } ) // first subscriber
observer.subscribe((data)=> { console.log('sec', data ) } ) // sec subscriber//通知订阅者值已更改
observer.notify(123) 输出将是
first 123123
sec 123123你的案子你必须先订阅那个观察者的任何位置
observer.subscribe((data)=> {
console.log('I got some data from firestore', data );
// Do some stuff
} );只需在提取函数中添加通知即可。
const getNBAScoreKey = () => {
return new Promise(resolve => {
scoresRef.onSnapshot(nbaScoreKeySnapshot => {
console.log("the value inside the score key: " + nbaScoreKeySnapshot.data()["FantScores"]);
let data = nbaScoreKeySnapshot.data();
observer.notify(data);
resolve(data);
});
});
}此外,通过调用observer.data,您可以随时获取数据,从而返回最新的数据。
确保在全局范围内或在单独的文件和导出观察者变量上定义了观察者,然后在数据将被共享的任何地方导入该文件。
https://stackoverflow.com/questions/57733773
复制相似问题