![](/img/trans.png)
[英]Can someone explain why my modal isn't working. I think it has to do with my populateEpisodes function because the getEpisodes array is returned fine
[英]How do I rewrite this Firebase function so my returned array isn't empty?
我正在使用Firebase,但無法讓陣列返回我正在查詢的Firebase數據。 我嘗試填充的數組隨機返回空。 最有效的方法是什么?
const getCityData = function ( ) {
const dataRef = firebaseRef.child("cities");
const cities = [];
let cityItem = null;
dataRef.orderByChild("name").on("child_added", function ( snapshot ) {
cityItem = snapshot.val();
if ( cityItem.name && cityItem.isListable ) {
cities.push( cityItem );
}
});
return (cities);
};
我已經根據一些答案編輯了我的代碼,但不幸的是仍然無法獲取它。 在這一部分中,我可以將內容納入控制台中的代碼中並執行它。 除此之外,Firebase的.forEach部分沒有中斷。 仍然迷路。
const getCityDataAndThen = function (callback) {
const dataRef = firebaseRef.child("cities");
const cities = [];
let city = null;
dataRef.orderByChild("name").once("value", function ( snapshot ) {
snapshot.forEach(function ( citySnapshot ) {
city = citySnapshot.val();
if ( city.name && city.isListable ) {
cities.push( city );
}
});
});
callback(cities);
};
const getCityData = function () {
getCityDataAndThen(function (cities) {
return (cities);
});
};
當數據尚不可用時,您將返回城市。 您應該在getCityData中返回一個Promise對象,而不是任何數組。 並在數據可用時使用promise.then。
像這樣
function GetById(id) {
var child = ref.child("users").child(id);
var fireObj = $firebaseObject(child);
return fireObj;
}
現在,一旦獲得fireObj,就可以像使用它一樣。
然后在數據可用時調用。
fireObject.then(function(){
});
正如Sushil所說,您不能返回尚未加載的數據。
您的解決方案是:
在這里,我將堅持選項1。
const getCityDataAndThen = function (callback) {
const dataRef = firebaseRef.child("cities");
const cities = [];
let cityItem = null;
dataRef.orderByChild("name").once("value", function ( snapshot ) {
snapshot.forEach(function(citySnapshot) {
citySnapshot = snapshot.val();
if ( cityItem.name && cityItem.isListable ) {
cities.push( cityItem );
}
});
});
callback (cities);
};
您現在可以按以下方式調用它:
getCityDataAndThen(function(cities) {
console.log(cities);
});
您會注意到,我切換為使用once('value'
,因為使用on('child_added'
您沒有明確的時間來完成孩子們的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.