abhishek verma
abhishek verma

Reputation: 43

sequencial execution of foreach loop in firebase

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
  

Upvotes: 2

Views: 198

Answers (2)

abhishek verma
abhishek verma

Reputation: 43

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
    );

Upvotes: 0

Peter Haddad
Peter Haddad

Reputation: 80914

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

Upvotes: 1

Related Questions