2

I have a realtime database from Firebase, where data is stored in single strings not in objects. Problem is foreach loop executes at last, where as it need to be run first (i mean sequential). It comes out from the loop without performing its jobs.

exports.room_server = functions.database.ref(`/${Role.ROOM_REQUEST}/{room}`)
    .onCreate((snapshot,context)=>{

// her ref.once is refrence to another node of database
   ref.limttolast(3).once("value",function(snap){
       snap.forEach(function (usr) {
        adm = usr.val();
        console.log("admin " +  adm);
      });
      }).catch();
       
       console.log(" cl " + adm);
    });
//  cl undefined is shown first
// then it comes
// admin abc
// admin you
// admin me

   //result should be 
   //admin abc 
   //admin you
   //admin me
//cl me
  

0

2 Answers 2

1

You get this output:

//  cl undefined is shown first
// then it comes
// admin abc
// admin you
// admin me

Because once() is asynchronous which means it will move to another task before it finishes retrieving the data, that's why console.log(" cl " + adm); is executed first.

You can do the following:

ref.limitToLast(3).once("value").then((snapshot) => {
    snapshot.forEach((usr) => {
     adm = usr.val();
     console.log(" cl " + adm);
     console.log("admin " +  adm);
     });
 }).catch((e) =>{
    console.log(e);
 });

The then() method returns a Promise, it will be called when the Promise is fulfilled or rejected.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

Sign up to request clarification or add additional context in comments.

1 Comment

I want to correct, 'snap' in second line it should be 'snapshot', matching it with keyword in first line. And after .then() method there should be .catch() method to handle any exception
0

Answer given above will also work but, here is another way to do it same. It will be almost same.

   ref.limttolast(3).once("value").then((snapshot) => {
       
       snapshot.forEach((usr) => {
        adm = usr.val();
        console.log(" cl " + adm);
        console.log("admin " +  adm);
        }); // end of foreach loop
        
        return adm; 
        //return will wrap it as promise which will be fulfilled or rejected
        // return will send it to next .then() method 
    })
    .then( value_of_adm =>{
        // value_of_adm = adm
       console.log("cl" + value_of_adm);
    })
    .catch(
      // enter your code here
      // if u dont write code here no problem it will work fine
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.