使用Firebase读取Node.js Promise [英] Reading a nodejs promise with firebase

查看:57
本文介绍了使用Firebase读取Node.js Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用nodejs从firebase读取一个值.我的阅读部分正常工作.但是我无法输出该值.

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.

我对Node.js很陌生,我相信我在阅读Promise时做错了什么.

I'm pretty new to nodejs and I believe I'm doing something wrong with reading promises.

这是我的代码

#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')
            })
        }
    }
}());

当我执行 node index.js 时,我得到了 -----------从Firebase读取... ,但没有得到--从index.js输出值,它就挂在那里.

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 ?

我的节点版本是-v8.10.0

my node version is - v8.10.0

推荐答案

这是因为 once()是异步的并立即返回.这会导致您的 readValue 立即返回无值的值.传递给 once()的函数将在一段时间后调用.

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.

如果您要创建一个查询Realtime Database的函数(或使用异步工作执行任何操作),则它应返回一个promise,以便调用方可以在其上使用 then()来获取结果.只要它准备好了.

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.

这篇关于使用Firebase读取Node.js Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆