import Firebase from './Firebase'
import videoManager from './videoManage';
async function getAllDatabaseLocations() {
await let ref = Firebase.database().ref("locations")
var user_locations = [];
ref.on("value", function (snapshot) {
snapshot.forEach(function (datas) {
const data = datas.val();
vid_manage = new videoManager(data.videourl);
vid_ref = vid_manage.getLocationVideoUrl();
vid_ref.getDownloadURL().then(function (url) {
videourl = url;
}).catch(function (error) {
});
let lokation = data.lokation;
let videourl = data.videourl;
let openinghours = data.openinghours;
let links = data.links;
let Lokationer = {
lokation: lokation,
videoUrl: videourl,
openingshours: openinghours,
links: links
};
console.log("Location objects are: ", Lokationer);
user_locations.push(Lokationer);
// location_obj.push(Lokationer);
});
});
return user_locations;
}
export default getAllDatabaseLocations;
即使循环内的控制台按我的预期进行打印,此方法也总是返回一个空数组。如何使用async和await属性,以便返回一个数组,其中包含所有Lokationer对象。
最佳答案
由于异步ref.on("value")
回调,您需要返回一个新的Promise。
function getAllDatabaseLocations() {
return new Promise(resolve => {
ref.on("value", function (snapshot) {
...
// when done filling the array
resolve(user_locations);
});
});
}
const userLocations = await getAllDatabaseLocations(); // user_locations