Returning an Array using Firebase

Deadly 提交于 2019-12-19 10:54:27

问题


Trying to find the best-use example of returning an array of data in Node.js with Q library (or any similar library, I'm not partial) when using Firebase .on("child_added");

I've tried using Q.all() but it never seems to wait for the promises to fill before returning. This is my current example:

function getIndex()
{
    var deferred = q.defer();

    deferred.resolve(new FirebaseIndex( Firebase.child('users').child(user.app_user_id).child('posts'), Firebase.child('posts') ) );

    return deferred.promise;
}

function getPost( post )
{
    var deferred = q.defer();
    deferred.resolve(post.val());
    return deferred.promise;
}

function getPosts()
{
    var promises = [];          

    getIndex().then( function (posts) {
        posts.on( 'child_added', function (_post) {
            promises.push( getPost(_post) );
        });
    });
    return q.all(promises);
}

回答1:


The problem occurs in getPosts(). It pushes a promise into your array inside an async function--that won't work since q.all is called before the promise objects have been added.

Also, child_added is a real-time event notification. You can't use that as a way to grab "all of the data" because there is no such thing as "all"; the data is constantly changing in real-time environments. FirebaseIndex is also using child_added callbacks internally, so that's not going to work with this use case either.

You can grab all of the posts using the 'value' callback (but not a specific subset of records) as follows:

function getPosts() {
   var def = q.defer();
   Firebase.child('users').once('value', function(snap) {
      var records = [];
      snap.forEach(function(ss) {
         records.push( ss.val() );
      });
      def.resolve(records);
   });
   return def.promise;
}

But at this point, it's time to consider things in terms of real-time environments. Most likely, there is no reason "all" data needs to be present before getting to work.

Consider just grabbing each record as they come in and appending them to whatever DOM or Array where they need to be stored, and working from an event driven model instead of a GET/POST centered approach.

With luck, you can bypass this use case entirely.



来源:https://stackoverflow.com/questions/17392166/returning-an-array-using-firebase

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!