使用Node.js从Object获取数据

时间:2017-10-26 09:15:26

标签: javascript node.js firebase firebase-realtime-database

我无法从此对象“快照”访问数据,我不知道原因:

[
{"action":"Afficher les détails ","cat":"Produits 1","image":"https://www.google.fr","lien":"https://www.google.fr","nom_intent":"1","reponse":"réponse 1","scat":"scat1"},
{"action":"Afficher les détails ","cat":"Produits 2","image":"https://www.google.fr","lien":"https://www.google.fr","nom_intent":"2","reponse":"réponse 2","scat":"scat2"},
{"action":"Afficher les détails ","cat":"Produits 3","image":"https://www.google.fr","lien":"https://www.google.fr","nom_intent":"3","reponse":"réponse 3","scat":"scat3"}
]

我用这段代码得到了这个对象:

function getFirebaseData(endpoint){
      return 
      firebase.database().ref('intent/'+endpoint).once("value", 
      function(snapshot){
            return snapshot.val();
      });
    }

Promise.all([
  getFirebaseData(entities.intent[0].value), 
  getFirebaseData(entities.intent[1].value), 
  getFirebaseData(entities.intent[2].value)
]).then(function(snapshots) {

});

并试图像这样访问:

var action0 = snapshots[0].action;

action0undefined

1 个答案:

答案 0 :(得分:0)

我找到了完成这件事的诀窍!
我对一个数组进行了描述:var firebaseData = [];然后我将所有值都推到了它:

function getFirebaseData(endpoint){
          return firebase.database().ref('intent/'+endpoint).once("value", function(snapshot){
                firebaseData.push(snapshot.val());
          });
        }

当Promises完成后,我可以这样访问:

Promise.all([
    getFirebaseData(entities.intent[0].value), 
    getFirebaseData(entities.intent[1].value), 
    getFirebaseData(entities.intent[2].value)])
.then(function(snapshots) {
         var zero = firebaseData[0];
         var first = firebaseData[1];
});