2017-03-01 19 views
1

可有人请解释如何用火力地堡使用承诺下面我的代码:火力地堡等待承诺火灾之前加载数据库中的数据

 var p = new Promise(function(resolve, reject) { 
      var data=null; 

      var ref = db.ref("/"); 
      ref.once("value", function(snapshot) { 
       data = snapshot.val(); 

      }); 

      data.onload = function() { 
       console.log(data+" onload"); 

       if (data!=null) { 
        resolve('Success!'); 
       } 
       else { 
        reject('Failure!'); 
        console.log('failed'); 
       } 

      } 

     }); 

     p.then(function() { 
      /* do something with the result */ 
      console.log(data+" done"); 
     }).catch(function() { 
      /* error :(*/ 
      console.log("error"); 
     }); 

我想等到我从data = snapshot.val();我之前“回音”调用我的下一个功能。什么是正确的方式去做这件事?我显然不理解承诺。我正在尝试遵循this教程。

+0

看着你的代码,它是你需要刷新的firebase!忽略承诺代码,其余代码看起来完全错误 –

+0

我的意思是,你的'var p'可以简单地变成'var p = db.ref(“/”)。once(“value”);' - 因为'once '答应了! ...然后它是'p.then(函数(结果){...对结果做一些事情...})' –

回答

2

承诺直接内置到firebase中。

var ref = firebase.database().ref(); 

ref.once('value') 
    .then(function (result) { 
    // This only happens after the data has been returned 
    console.log(result.val()); 
    }) 
    .catch(function (err) { 
    // This is where errors land 
    console.log('Error', err.code); 
    }); 

Firebase的第3版已经覆盖,因此您不需要创建容器承诺。 :)