0

Below is the working code to access data form firebase. It uses global variable 'Data' array to send it to the final callback function. But I don't want to declare global variable. So is there anyway I can pass my data to every callbacks after it ? below is the code.

var data = {};

getData('myKey', function(){
 console.log("myCompleteData: "+ data); //both Id and finalData 
});

var getData= function(key,callback) {
    return fireproof.child("data").child(key)
    .then(CUSTOM_getData)
    .then(callback)
}

function CUSTOM_getData(snapshot) {

        var id= snapshot.val().id;
        data.id= id;

  return {
    then: function(callback) {

    fireproof.child("otherData").child(data.id)
    .then(CUSTOM_getSomethingFromId)
    .then(callback)
      }

  };
}

function CUSTOM_getSomethingFromId(snapshot) {

            var finalData = snapshot.val().finalData;
            data.finalData = finalData;

      return {
        then: function(callback) {

        callback(data);
          }  
      };
}

And I am new to Node.js. So please let me know if this approach is correct :)

Kazim Homayee
  • 739
  • 6
  • 8
  • 1
    Why are you rolling your own promise :O? – Benjamin Gruenbaum Jan 03 '16 at 09:19
  • So that I can pass variables to the previous callback. But i know the approach was incorrect. I have fixed this. Please review my code below. P.S: I am new to Node.js – Kazim Homayee Jan 04 '16 at 07:07
  • Your "new code" is still incorrect. Do not roll your own promise implementation it is really hard - for example if your promise is passed somewhere that calls the `then` callback with a promise as its return value - your code behaves incorrectly. Namely - if you roll `then` you have to roll a full blown promise impl. – Benjamin Gruenbaum Jan 04 '16 at 07:37
  • Can you please help me with my code below ? – Kazim Homayee Jan 04 '16 at 08:34

1 Answers1

0

Working code:

var getSomeData = function(key,callback) {

    var data = {};

    fireproof.authWithCustomToken(nconf.get('config:someToken')).then(function(){

        return fireproof.child("data").child(key)

    }).then(function(snapshot){

            data.id= snapshot.val().id;

            return fireproof.child("otherData").child(data.id)

    }).then(function(snapshot){

            data.finalData = snapshot.val().finalData;

            callback(data);

    }, function(error){
            console.log('Error: '+error);
    });
}
Kazim Homayee
  • 739
  • 6
  • 8