问题
I'm trying to read a value from firebase using nodejs. I got the reading part working. However I cannot get the value to be output.
I'm pretty new to nodejs and I believe I'm doing something wrong with reading promises.
Here is my code
#index.js
var firebase = require('./firebase');
firebase.readValue(data => {
console.log('--- output value')
console.log(data);
})
#firebase.js
(function(){
var admin = require('firebase-admin');
var serviceAccount = require('./keys/<keyfile>');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: '<url>'
});
module.exports = {
readValue: function(){
var firebase = admin.database().ref("nemo/garage/status");
firebase.once("value").then(function(snapshot){
console.log("----------- reading from firebase...")
console.log(snapshot.val())
return snapshot;
}, function(error){
console.log('error')
})
}
}
}());
When I do node index.js I get ----------- reading from firebase... but not the --- output value from index.js and it just hangs there.
What am I doing wrong in reading this promise ?
my node version is - v8.10.0
回答1:
That's because once() is asynchronous and returns immediately. This causes your readValue to return immediately with no value. The function you passed to once() will be invoked some time later.
If you want to make a function that queries Realtime Database (or does anything with async work), it should return a promise so that the caller can use then() on it to get the result whenever it becomes ready.
来源:https://stackoverflow.com/questions/50031956/reading-a-nodejs-promise-with-firebase