我想编写一个返回对象的查询函数。问题是,在我的例子中,函数返回 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提到,您不能从异步调用返回结果。
您可以做的是使用一种方法处理您的结果,并直接调用您的异步调用而不期望返回结果:
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);
我想这完全取决于您要对数据执行的操作以及您希望引用数据的次数。
注意:我确实建议将您的脚本放在一个独立的函数中以避免添加私有(private)函数(特定于单个功能),这样您就不会污染您的全局命名空间。
Ben Alman写了一篇关于立即调用函数表达式 (IIFE) 的好文章,或者您可以使用 JavaScript namespace .
编辑:作为adolfosrs建议,你也可以使用 promises但请记住什么browsers你愿意支持。