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

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -