javascript - First finish reading data from Firebase and then do something else -
so problem empty array returned because reading data firebase not finished yet. using method still executes inside before.
var userslist = []; const ref = firebase.database().ref() ref.child('users').once('value').then(snap => { snap.foreach(childsnap => { const key = childsnap.key ref.child(`users/${key}/points`).on('value', function(snapper) { var points = snapper.val() userslist.push({uid: key, points: points}) }) }) }).then(function() { console.log(userslist) })
using then()
not magical solution. need return promise within callback, code not doing. in case want final then()
invoked once users loaded, need return promise resolves when done.
const ref = firebase.database().ref() ref.child('users').once('value').then(snap => { var promises = []; snap.foreach(childsnap => { const key = childsnap.key promises.push( ref.child(`users/${key}/points`).once('value') ); }); return promise.all(promises); }).then(function(snapshots) { return snapshots.map(snapper => { var points = snapper.val() return {uid: key, points: points}; }) }).then(function(userslist) { console.log(userslist) })
Comments
Post a Comment