Firebase查询函数返回未定义 [英] Firebase query function returns undefined

查看:56
本文介绍了Firebase查询函数返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个返回对象的查询函数.问题是,就我而言,该函数返回 undefined .

I want to write a query function which returns an object. The problem is, in my case the function returns undefined.

var filterDataAccordingToDate = function (ref, startTime, endTime) {

    var filteredObj = {};

    ref.orderByChild('date').startAt(startTime).endAt(endTime)
    .once('value', function(snap) {
       filteredObj = snap.val();

       console.log(util.inspect(filterDataAccordingToDate(filteredObj, false, null));
      //Returns the correct object

       return filteredObj;
    });  
}

console.log("DATA RETURNED: " + util.inspect(filterDataAccordingToDate(travelRef, 1466439004, 1466439011), false, null));
// DATA RETURNED: undefined

推荐答案

正如 Ami 所述,您可以'不能从异步调用返回结果.

As Ami mentions, you can't return a result from an asynchronous call.

您可以做的是使用一种方法来处理结果,并直接调用异步调用而无需返回结果:

What you could do is process your results using a method and simply call your asynchronous call directly without expecting a return result:

var filterDataAccordingToDate = function (ref, startTime, endTime) {
  ref.orderByChild('date').startAt(startTime).endAt(endTime)
    .once('value', function(snap) {
      var filteredObj = snap.val();

      console.log(util.inspect(filterDataAccordingToDate(filteredObj, false, null));
      doSomethingWith(filteredObj);
  });  
}

function doSomethingWith(obj) {
  console.log("DATA RETURNED: " + util.inspect(obj, false, null));
}

filterDataAccordingToDate(travelRef, 1466439004, 1466439011);

我想这一切都取决于您想对数据做些什么以及您希望引用多少次.

I suppose it all depends on what you want to do with your data and how many times you wish to reference it.

注意:我建议您将脚本放置在一个自包含函数中,以避免添加私有功能(特定于单个功能),以免污染全局名称空间. Ben Alman 写了一篇有关立即调用函数的不错的帖子表达式(IIFE),也可以使用 JavaScript名称空间.

Note: I do suggest placing your script in a self-contained function to avoid adding private functions (specific to a single piece of functionality) so that you don't pollute your global namespace. Ben Alman wrote a nice post about Immediately-Invoked Function Expressions (IIFE) or you can make use of a JavaScript namespace.

编辑:按照 adolfosrs 的建议,您也可以使用浏览器您希望支持的.

Edit: As adolfosrs suggests, you can also use promises but keep in mind what browsers you wish to support.

这篇关于Firebase查询函数返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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