1
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; 

This method always returns an empty array, even if the console inside the loop prints as i expected? How to use async and await property so as to return an array with all Lokationer objects inside on it.

1
  • The await would go before an async function or function that returns a promise. I can't speak to whether this would be applicable to your Firebase call, but if it is you would put await to the right of the = in the assignment, just before the call that you want to wait for a result from. So let ref = await Firebase.[...] Commented Feb 4, 2019 at 18:13

1 Answer 1

1

You'll need to return a new promise because of the asynchronous ref.on("value") callback.

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I got it working. But I can't get all object pushed into user_locations array. Only few objects get pushed into user_locations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.