我的功能javascript不能完全正常工作

问题描述 投票:-1回答:1

我的JavaScript函数无法完全正常运行。

HTML:

<body onload="initialize();">

    <div class="topnav">
      <a href="./index.html">Accueil</a>
      <a class="active" href="./mycave.html">Ma cave</a>
      <a href="./mylist.html">Ma liste</a>
      <a href="./account.html">Mon compte</a>
    </div>

    <div style="padding-left:16px" id="main">

    </div>    

JavaScript:

function initialize(){
        var main = document.getElementById('main');
        var database = firebase.database();
        var dbref = database.ref(uid+'/cave');

        dbref.once('value').then(function(snapshot){
          snapshot.forEach(function(childsnapshot){
            console.info('Vin : ', childsnapshot);
            var div = document.createElement('div');
            div.setAttribute('class', 'card');
            var header = document.createElement('h1')
            header.appendChild(document.createTextNode(childsnapshot.val().nom));
            div.appendChild(header);
            var viticulteur = document.createElement('p');
            viticulteur.appendChild(document.createTextNode(childsnapshot.val().viticulteur));
            div.appendChild(viticulteur);
            var nb_bouteilles = document.createElement('p');
            nb_bouteilles.setAttribute('class', 'price');
            nb_bouteilles.appendChild(document.createTextNode(childsnapshot.val().number));
            div.appendChild(nb_bouteilles);
            var open = document.createElement('p');
            var open_btn = document.createElement('button');
            open_btn.appendChild(document.createTextNode('Voir'));
            open.appendChild(open_btn);
            div.appendChild(open);
            main.appendChild(div);
          });
        });
        console.info('Function terminated!');
      }

当加载文档时,日志控制台仅在写'终止的功能'

[当我在控制台中执行功能时,控制台将写'Vin:cn {node_:Je,ref_:Oi,index_:Pe}',然后是'Function Terminated'

有人可以告诉我它可能来自哪里吗?

javascript firebase firebase-realtime-database
1个回答
0
投票

这是因为一旦获得该值,dbref.once('value').then...部分就会异步执行。这意味着程序将跳过dbref.once部分并继续执行,将其放到console.info部分。永恒(到计算机)之后,dbref.once('value').then...部分可能在您的函数完成之后执行。

[基本上,dbref.once('value').then...函数仅在数据存在并准备就绪时才执行,这需要时间,因此它是异步完成的,计算机将在等待数据的同时继续执行。您将需要计划稍后在未知时间执行的函数,因此放置占位符值可能是一个不错的选择,并且该函数可以使用实际数据覆盖这些默认值。

© www.soinside.com 2019 - 2024. All rights reserved.