【问题标题】:sequencial execution of foreach loop in firebaseFirebase中foreach循环的顺序执行
【发布时间】:2020-08-14 14:05:04
【问题描述】:

我有一个来自 Firebase 的实时数据库,其中数据存储在单个字符串中,而不是对象中。问题是 foreach 循环最后执行,因为它需要首先运行(我的意思是顺序)。它从循环中出来而不执行它的工作。

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
  

【问题讨论】:

    标签: javascript typescript firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    你得到这个输出:

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

    因为once() 是异步的,这意味着它将在完成检索数据之前移动到另一个任务,这就是为什么首先执行console.log(" cl " + adm);

    您可以执行以下操作:

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

    then() 方法返回一个Promise,它会在Promise 被执行或拒绝时被调用。

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

    【讨论】:

    • 我要更正,第二行中的“快照”应该是“快照”,与第一行中的关键字匹配。在 .then() 方法之后应该有 .catch() 方法来处理任何异常
    【解决方案2】:

    上面给出的答案也可以,但是,这是另一种方法。几乎是一样的。

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

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 1970-01-01
      • 2016-08-10
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      相关资源
      最近更新 更多