2017-03-01 74 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版已經覆蓋,因此您不需要創建容器承諾。 :)