Returning a value from callback functionIs there an “exists” function for jQuery?Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How do I remove a property from a JavaScript object?var functionName = function() vs function functionName() Set a default parameter value for a JavaScript functionHow can I get query string values in JavaScript?Sort array of objects by string property valueevent.preventDefault() vs. return falseHow do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?

Can GPL and BSD licensed applications be used for government work?

Is an easily guessed plot twist a good plot twist?

How were the LM astronauts supported during the moon landing and ascent? What were the max G's on them during these phases?

Moving files accidentally to an not existing directory erases files?

This message is flooding my syslog, how to find were it comes from?

Will LSST make a significant increase in the rate of astronomical event alerts?

401(k) investment after being fired. Do I own it?

Sextortion with actual password not found in leaks

What should I say when a company asks you why someone (a friend) who was fired left?

Would it be a good idea to memorize relative interval positions on guitar?

Which creatures count as green creatures?

kids pooling money for Lego League and taxes

What is a Union Word™?

High income, sudden windfall

Terence Tao - type books in other fields?

Problem loading expl3 in plain TeX

What are the exact meanings of roll, pitch and yaw?

Spacing setting of math mode

Why keep the bed heated after initial layer(s) with PLA (or PETG)?

How did C64 games handle music during gameplay?

Why no ";" after "do" in sh loops?

Who has jurisdiction for a crime committed in an embassy?

Where to place an artificial gland in the human body?

How do I run a game when my PCs have different approaches to combat?



Returning a value from callback function


Is there an “exists” function for jQuery?Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How do I remove a property from a JavaScript object?var functionName = function() vs function functionName() Set a default parameter value for a JavaScript functionHow can I get query string values in JavaScript?Sort array of objects by string property valueevent.preventDefault() vs. return falseHow do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








-1















I am using the on() method to retrieve a data snapshot in our database, but I need to be able to store this snapshot value so that I can use it to retrieve another separate snapshot.



Here is what our database looks like:
Firebase Real-Time Database



There is a node for users and a separate node for devices. Each user has a child "devices" which is a list of devices associated with that user. The user that I have expanded only has one device.



What I am trying to do is store this deviceID, and then do a separate query to find that device in the "Devices" node. Here is what my code looks like:



let uid = fireBaseUser.uid; 
//get a reference to the database
let database = firebase.database();
let ref = database.ref("users/").child(uid).child("devices");
ref.on("value", getData);


And then the callback function looks like this:



function getData(data)

currentDevice = Object.keys(data.val())[0];
console.log("current device: " + currentDevice);



which is just grabbing the first device in the users device list and printing it to the console. I am trying to figure out how to
return this value so that I can use it when getting the data from the Devices tree. Which, I'm guessing,
would look something like this:



let deviceRef = database.ref("devices/").child(retrievedValue);
deviceRef.on("value", getData2);


Where retrievedValue is the deviceID that I got from the first query.



Is it possible to do this in javascript, or is there a better way? I know similar questions have already been asked, but I've found all the examples I've seen online to be really confusing and not very helpful for me. Any help at all would be super appreciated because I am kind of stuck on this. Thanks!










share|improve this question






























    -1















    I am using the on() method to retrieve a data snapshot in our database, but I need to be able to store this snapshot value so that I can use it to retrieve another separate snapshot.



    Here is what our database looks like:
    Firebase Real-Time Database



    There is a node for users and a separate node for devices. Each user has a child "devices" which is a list of devices associated with that user. The user that I have expanded only has one device.



    What I am trying to do is store this deviceID, and then do a separate query to find that device in the "Devices" node. Here is what my code looks like:



    let uid = fireBaseUser.uid; 
    //get a reference to the database
    let database = firebase.database();
    let ref = database.ref("users/").child(uid).child("devices");
    ref.on("value", getData);


    And then the callback function looks like this:



    function getData(data)

    currentDevice = Object.keys(data.val())[0];
    console.log("current device: " + currentDevice);



    which is just grabbing the first device in the users device list and printing it to the console. I am trying to figure out how to
    return this value so that I can use it when getting the data from the Devices tree. Which, I'm guessing,
    would look something like this:



    let deviceRef = database.ref("devices/").child(retrievedValue);
    deviceRef.on("value", getData2);


    Where retrievedValue is the deviceID that I got from the first query.



    Is it possible to do this in javascript, or is there a better way? I know similar questions have already been asked, but I've found all the examples I've seen online to be really confusing and not very helpful for me. Any help at all would be super appreciated because I am kind of stuck on this. Thanks!










    share|improve this question


























      -1












      -1








      -1








      I am using the on() method to retrieve a data snapshot in our database, but I need to be able to store this snapshot value so that I can use it to retrieve another separate snapshot.



      Here is what our database looks like:
      Firebase Real-Time Database



      There is a node for users and a separate node for devices. Each user has a child "devices" which is a list of devices associated with that user. The user that I have expanded only has one device.



      What I am trying to do is store this deviceID, and then do a separate query to find that device in the "Devices" node. Here is what my code looks like:



      let uid = fireBaseUser.uid; 
      //get a reference to the database
      let database = firebase.database();
      let ref = database.ref("users/").child(uid).child("devices");
      ref.on("value", getData);


      And then the callback function looks like this:



      function getData(data)

      currentDevice = Object.keys(data.val())[0];
      console.log("current device: " + currentDevice);



      which is just grabbing the first device in the users device list and printing it to the console. I am trying to figure out how to
      return this value so that I can use it when getting the data from the Devices tree. Which, I'm guessing,
      would look something like this:



      let deviceRef = database.ref("devices/").child(retrievedValue);
      deviceRef.on("value", getData2);


      Where retrievedValue is the deviceID that I got from the first query.



      Is it possible to do this in javascript, or is there a better way? I know similar questions have already been asked, but I've found all the examples I've seen online to be really confusing and not very helpful for me. Any help at all would be super appreciated because I am kind of stuck on this. Thanks!










      share|improve this question
















      I am using the on() method to retrieve a data snapshot in our database, but I need to be able to store this snapshot value so that I can use it to retrieve another separate snapshot.



      Here is what our database looks like:
      Firebase Real-Time Database



      There is a node for users and a separate node for devices. Each user has a child "devices" which is a list of devices associated with that user. The user that I have expanded only has one device.



      What I am trying to do is store this deviceID, and then do a separate query to find that device in the "Devices" node. Here is what my code looks like:



      let uid = fireBaseUser.uid; 
      //get a reference to the database
      let database = firebase.database();
      let ref = database.ref("users/").child(uid).child("devices");
      ref.on("value", getData);


      And then the callback function looks like this:



      function getData(data)

      currentDevice = Object.keys(data.val())[0];
      console.log("current device: " + currentDevice);



      which is just grabbing the first device in the users device list and printing it to the console. I am trying to figure out how to
      return this value so that I can use it when getting the data from the Devices tree. Which, I'm guessing,
      would look something like this:



      let deviceRef = database.ref("devices/").child(retrievedValue);
      deviceRef.on("value", getData2);


      Where retrievedValue is the deviceID that I got from the first query.



      Is it possible to do this in javascript, or is there a better way? I know similar questions have already been asked, but I've found all the examples I've seen online to be really confusing and not very helpful for me. Any help at all would be super appreciated because I am kind of stuck on this. Thanks!







      javascript firebase firebase-realtime-database






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 16:02









      chazsolo

      5,5471 gold badge12 silver badges34 bronze badges




      5,5471 gold badge12 silver badges34 bronze badges










      asked Mar 26 at 15:59









      bgriffybgriffy

      112 bronze badges




      112 bronze badges






















          2 Answers
          2






          active

          oldest

          votes


















          1














          In order to achieve that, you have to modify your callback as following:



          function getData(data, callback)

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          callback(currentDevice)



          Then we you call your callback from within the code, do it like this:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData((this_is_the_value_from_inside_callback) =>
          console.log(`your value: $this_is_the_value_from_inside_callback`)
          );


          You can also try to run this little snippet (I used PlayCode), to see it more friendly testing environment



          somefunction = (data, callback) => 

          console.log(`data: $data`)
          data += 100
          console.log(`data: $data`)
          callback(data)


          somefunction(100, (dataReturned) =>
          console.log(`data returned: $dataReturned`)
          )





          share|improve this answer























          • Thanks for the response! I am getting the following error though: TypeError: data.val is not a function. I am guessing the data snap shot is not getting passed in correctly? Any ideas? I really appreciate it!

            – bgriffy
            Mar 26 at 17:29











          • Sorry for late reply! I haven't used Firebase before, so I can't show you a real example where this could work. I tried to apply basic 'callback' functionality to a function, to demonstrate how you could return a value from it. I looked into this documentation link and my first suggestion would be to modify getData inside ref.on to accept snapshot and a callback. So it would look something like this: ref.on("value", getData(snapshot, (callback) => ). Let me know if that helps

            – Irek
            Mar 27 at 0:11


















          1














          You have to learn about promises and asynchronous programming. Here are two ways to do what you want:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.once("value").then((data)
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          return deviceRef.once("value");
          ).then((value)
          console.log("value is " + value);
          )


          or with async/await:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          let data = await ref.once("value")
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          let value = await deviceRef.once("value");
          console.log("value is " + value);


          I'm more confident about the second one as I'm typing these without testing.



          These links would be helpful to start learning this stuff:
          https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html
          https://firebase.google.com/docs/functions/terminate-functions



          Edit: I fixed the code above by replacing on with once. However now this is not listening to changes in the db anymore. To correct your code to listen to user's device changes:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData);

          function getData(data) // may need to place this before the code above

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);

          // no need to listen to this, as a change in one device would fire
          // for every user. you probably don't want that.
          deviceRef.once("value", (data)
          console.log(data);
          );






          share|improve this answer

























          • Thanks for your suggestions. I tried each of your suggested methods, but for both I am getting the error Query.on failed: Was called with 1 argument. Expects at least 2..

            – bgriffy
            Mar 26 at 18:02











          • Ok I edited the code and provided an alternative. Still did not test, hope it works :)

            – Gazihan Alankus
            Mar 26 at 19:06













          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55361440%2freturning-a-value-from-callback-function%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          In order to achieve that, you have to modify your callback as following:



          function getData(data, callback)

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          callback(currentDevice)



          Then we you call your callback from within the code, do it like this:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData((this_is_the_value_from_inside_callback) =>
          console.log(`your value: $this_is_the_value_from_inside_callback`)
          );


          You can also try to run this little snippet (I used PlayCode), to see it more friendly testing environment



          somefunction = (data, callback) => 

          console.log(`data: $data`)
          data += 100
          console.log(`data: $data`)
          callback(data)


          somefunction(100, (dataReturned) =>
          console.log(`data returned: $dataReturned`)
          )





          share|improve this answer























          • Thanks for the response! I am getting the following error though: TypeError: data.val is not a function. I am guessing the data snap shot is not getting passed in correctly? Any ideas? I really appreciate it!

            – bgriffy
            Mar 26 at 17:29











          • Sorry for late reply! I haven't used Firebase before, so I can't show you a real example where this could work. I tried to apply basic 'callback' functionality to a function, to demonstrate how you could return a value from it. I looked into this documentation link and my first suggestion would be to modify getData inside ref.on to accept snapshot and a callback. So it would look something like this: ref.on("value", getData(snapshot, (callback) => ). Let me know if that helps

            – Irek
            Mar 27 at 0:11















          1














          In order to achieve that, you have to modify your callback as following:



          function getData(data, callback)

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          callback(currentDevice)



          Then we you call your callback from within the code, do it like this:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData((this_is_the_value_from_inside_callback) =>
          console.log(`your value: $this_is_the_value_from_inside_callback`)
          );


          You can also try to run this little snippet (I used PlayCode), to see it more friendly testing environment



          somefunction = (data, callback) => 

          console.log(`data: $data`)
          data += 100
          console.log(`data: $data`)
          callback(data)


          somefunction(100, (dataReturned) =>
          console.log(`data returned: $dataReturned`)
          )





          share|improve this answer























          • Thanks for the response! I am getting the following error though: TypeError: data.val is not a function. I am guessing the data snap shot is not getting passed in correctly? Any ideas? I really appreciate it!

            – bgriffy
            Mar 26 at 17:29











          • Sorry for late reply! I haven't used Firebase before, so I can't show you a real example where this could work. I tried to apply basic 'callback' functionality to a function, to demonstrate how you could return a value from it. I looked into this documentation link and my first suggestion would be to modify getData inside ref.on to accept snapshot and a callback. So it would look something like this: ref.on("value", getData(snapshot, (callback) => ). Let me know if that helps

            – Irek
            Mar 27 at 0:11













          1












          1








          1







          In order to achieve that, you have to modify your callback as following:



          function getData(data, callback)

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          callback(currentDevice)



          Then we you call your callback from within the code, do it like this:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData((this_is_the_value_from_inside_callback) =>
          console.log(`your value: $this_is_the_value_from_inside_callback`)
          );


          You can also try to run this little snippet (I used PlayCode), to see it more friendly testing environment



          somefunction = (data, callback) => 

          console.log(`data: $data`)
          data += 100
          console.log(`data: $data`)
          callback(data)


          somefunction(100, (dataReturned) =>
          console.log(`data returned: $dataReturned`)
          )





          share|improve this answer













          In order to achieve that, you have to modify your callback as following:



          function getData(data, callback)

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          callback(currentDevice)



          Then we you call your callback from within the code, do it like this:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData((this_is_the_value_from_inside_callback) =>
          console.log(`your value: $this_is_the_value_from_inside_callback`)
          );


          You can also try to run this little snippet (I used PlayCode), to see it more friendly testing environment



          somefunction = (data, callback) => 

          console.log(`data: $data`)
          data += 100
          console.log(`data: $data`)
          callback(data)


          somefunction(100, (dataReturned) =>
          console.log(`data returned: $dataReturned`)
          )






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 26 at 16:08









          IrekIrek

          1129 bronze badges




          1129 bronze badges












          • Thanks for the response! I am getting the following error though: TypeError: data.val is not a function. I am guessing the data snap shot is not getting passed in correctly? Any ideas? I really appreciate it!

            – bgriffy
            Mar 26 at 17:29











          • Sorry for late reply! I haven't used Firebase before, so I can't show you a real example where this could work. I tried to apply basic 'callback' functionality to a function, to demonstrate how you could return a value from it. I looked into this documentation link and my first suggestion would be to modify getData inside ref.on to accept snapshot and a callback. So it would look something like this: ref.on("value", getData(snapshot, (callback) => ). Let me know if that helps

            – Irek
            Mar 27 at 0:11

















          • Thanks for the response! I am getting the following error though: TypeError: data.val is not a function. I am guessing the data snap shot is not getting passed in correctly? Any ideas? I really appreciate it!

            – bgriffy
            Mar 26 at 17:29











          • Sorry for late reply! I haven't used Firebase before, so I can't show you a real example where this could work. I tried to apply basic 'callback' functionality to a function, to demonstrate how you could return a value from it. I looked into this documentation link and my first suggestion would be to modify getData inside ref.on to accept snapshot and a callback. So it would look something like this: ref.on("value", getData(snapshot, (callback) => ). Let me know if that helps

            – Irek
            Mar 27 at 0:11
















          Thanks for the response! I am getting the following error though: TypeError: data.val is not a function. I am guessing the data snap shot is not getting passed in correctly? Any ideas? I really appreciate it!

          – bgriffy
          Mar 26 at 17:29





          Thanks for the response! I am getting the following error though: TypeError: data.val is not a function. I am guessing the data snap shot is not getting passed in correctly? Any ideas? I really appreciate it!

          – bgriffy
          Mar 26 at 17:29













          Sorry for late reply! I haven't used Firebase before, so I can't show you a real example where this could work. I tried to apply basic 'callback' functionality to a function, to demonstrate how you could return a value from it. I looked into this documentation link and my first suggestion would be to modify getData inside ref.on to accept snapshot and a callback. So it would look something like this: ref.on("value", getData(snapshot, (callback) => ). Let me know if that helps

          – Irek
          Mar 27 at 0:11





          Sorry for late reply! I haven't used Firebase before, so I can't show you a real example where this could work. I tried to apply basic 'callback' functionality to a function, to demonstrate how you could return a value from it. I looked into this documentation link and my first suggestion would be to modify getData inside ref.on to accept snapshot and a callback. So it would look something like this: ref.on("value", getData(snapshot, (callback) => ). Let me know if that helps

          – Irek
          Mar 27 at 0:11













          1














          You have to learn about promises and asynchronous programming. Here are two ways to do what you want:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.once("value").then((data)
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          return deviceRef.once("value");
          ).then((value)
          console.log("value is " + value);
          )


          or with async/await:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          let data = await ref.once("value")
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          let value = await deviceRef.once("value");
          console.log("value is " + value);


          I'm more confident about the second one as I'm typing these without testing.



          These links would be helpful to start learning this stuff:
          https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html
          https://firebase.google.com/docs/functions/terminate-functions



          Edit: I fixed the code above by replacing on with once. However now this is not listening to changes in the db anymore. To correct your code to listen to user's device changes:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData);

          function getData(data) // may need to place this before the code above

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);

          // no need to listen to this, as a change in one device would fire
          // for every user. you probably don't want that.
          deviceRef.once("value", (data)
          console.log(data);
          );






          share|improve this answer

























          • Thanks for your suggestions. I tried each of your suggested methods, but for both I am getting the error Query.on failed: Was called with 1 argument. Expects at least 2..

            – bgriffy
            Mar 26 at 18:02











          • Ok I edited the code and provided an alternative. Still did not test, hope it works :)

            – Gazihan Alankus
            Mar 26 at 19:06















          1














          You have to learn about promises and asynchronous programming. Here are two ways to do what you want:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.once("value").then((data)
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          return deviceRef.once("value");
          ).then((value)
          console.log("value is " + value);
          )


          or with async/await:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          let data = await ref.once("value")
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          let value = await deviceRef.once("value");
          console.log("value is " + value);


          I'm more confident about the second one as I'm typing these without testing.



          These links would be helpful to start learning this stuff:
          https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html
          https://firebase.google.com/docs/functions/terminate-functions



          Edit: I fixed the code above by replacing on with once. However now this is not listening to changes in the db anymore. To correct your code to listen to user's device changes:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData);

          function getData(data) // may need to place this before the code above

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);

          // no need to listen to this, as a change in one device would fire
          // for every user. you probably don't want that.
          deviceRef.once("value", (data)
          console.log(data);
          );






          share|improve this answer

























          • Thanks for your suggestions. I tried each of your suggested methods, but for both I am getting the error Query.on failed: Was called with 1 argument. Expects at least 2..

            – bgriffy
            Mar 26 at 18:02











          • Ok I edited the code and provided an alternative. Still did not test, hope it works :)

            – Gazihan Alankus
            Mar 26 at 19:06













          1












          1








          1







          You have to learn about promises and asynchronous programming. Here are two ways to do what you want:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.once("value").then((data)
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          return deviceRef.once("value");
          ).then((value)
          console.log("value is " + value);
          )


          or with async/await:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          let data = await ref.once("value")
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          let value = await deviceRef.once("value");
          console.log("value is " + value);


          I'm more confident about the second one as I'm typing these without testing.



          These links would be helpful to start learning this stuff:
          https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html
          https://firebase.google.com/docs/functions/terminate-functions



          Edit: I fixed the code above by replacing on with once. However now this is not listening to changes in the db anymore. To correct your code to listen to user's device changes:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData);

          function getData(data) // may need to place this before the code above

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);

          // no need to listen to this, as a change in one device would fire
          // for every user. you probably don't want that.
          deviceRef.once("value", (data)
          console.log(data);
          );






          share|improve this answer















          You have to learn about promises and asynchronous programming. Here are two ways to do what you want:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.once("value").then((data)
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          return deviceRef.once("value");
          ).then((value)
          console.log("value is " + value);
          )


          or with async/await:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          let data = await ref.once("value")
          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);
          let value = await deviceRef.once("value");
          console.log("value is " + value);


          I'm more confident about the second one as I'm typing these without testing.



          These links would be helpful to start learning this stuff:
          https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html
          https://firebase.google.com/docs/functions/terminate-functions



          Edit: I fixed the code above by replacing on with once. However now this is not listening to changes in the db anymore. To correct your code to listen to user's device changes:



          let uid = fireBaseUser.uid; 
          //get a reference to the database
          let database = firebase.database();
          let ref = database.ref("users/").child(uid).child("devices");
          ref.on("value", getData);

          function getData(data) // may need to place this before the code above

          currentDevice = Object.keys(data.val())[0];
          console.log("current device: " + currentDevice);
          let deviceRef = database.ref("devices/").child(currentDevice);

          // no need to listen to this, as a change in one device would fire
          // for every user. you probably don't want that.
          deviceRef.once("value", (data)
          console.log(data);
          );







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 26 at 19:05

























          answered Mar 26 at 16:12









          Gazihan AlankusGazihan Alankus

          2,6681 gold badge14 silver badges26 bronze badges




          2,6681 gold badge14 silver badges26 bronze badges












          • Thanks for your suggestions. I tried each of your suggested methods, but for both I am getting the error Query.on failed: Was called with 1 argument. Expects at least 2..

            – bgriffy
            Mar 26 at 18:02











          • Ok I edited the code and provided an alternative. Still did not test, hope it works :)

            – Gazihan Alankus
            Mar 26 at 19:06

















          • Thanks for your suggestions. I tried each of your suggested methods, but for both I am getting the error Query.on failed: Was called with 1 argument. Expects at least 2..

            – bgriffy
            Mar 26 at 18:02











          • Ok I edited the code and provided an alternative. Still did not test, hope it works :)

            – Gazihan Alankus
            Mar 26 at 19:06
















          Thanks for your suggestions. I tried each of your suggested methods, but for both I am getting the error Query.on failed: Was called with 1 argument. Expects at least 2..

          – bgriffy
          Mar 26 at 18:02





          Thanks for your suggestions. I tried each of your suggested methods, but for both I am getting the error Query.on failed: Was called with 1 argument. Expects at least 2..

          – bgriffy
          Mar 26 at 18:02













          Ok I edited the code and provided an alternative. Still did not test, hope it works :)

          – Gazihan Alankus
          Mar 26 at 19:06





          Ok I edited the code and provided an alternative. Still did not test, hope it works :)

          – Gazihan Alankus
          Mar 26 at 19:06

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55361440%2freturning-a-value-from-callback-function%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript