Reading a nodejs promise with firebase

怎甘沉沦 提交于 2020-01-25 07:20:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!