Array.length总是等于0

时间:2017-07-24 06:35:00

标签: javascript arrays firebase firebase-realtime-database

我试图获取数组的长度,但即使控制台显示我推送了5个对象,我也总是0;

async function getDiaries() {
 return new Promise((resolve, reject) => {
  var url = firebase.database().ref('/diary');
  var diaries = [];
  url.on('value', (snap) => {
    snap.forEach((child) => {
        diaries.push({
          key: child.key,
          name: child.val().name,
          date: child.val().description,
          url: child.val().url,
          idOwner: child.val().idOwner
        });
    });
});
console.log(diaries.length);// get 0
resolve(diaries)
})}

这是控制台向我展示的内容 enter image description here

3 个答案:

答案 0 :(得分:1)

将console.log移动到您的回调函数中,否则它将主要在您的回调执行之前运行。换句话说:你得到一个0,因为此时的长度是 0。

答案 1 :(得分:1)

当然你会得到这个 0 ,因为这是你可以尝试的异步功能

async function getDiaries() {
 return new Promise((resolve, reject) => {
  var url = firebase.database().ref('/diary');
  var diaries = [];
  url.on('value', (snap) => {
    snap.forEach((child) => {
        diaries.push({
          key: child.key,
          name: child.val().name,
          date: child.val().description,
          url: child.val().url,
          idOwner: child.val().idOwner
        });
    });
    console.log(diaries.length);
    resolve(diaries);
});
})}

答案 2 :(得分:1)

url.on可能是异步的,这意味着您需要在回调中执行console.log

async function getDiaries() {
  return new Promise((resolve, reject) => {
    var url = firebase.database().ref('/diary');
    var diaries = [];
    url.on('value', (snap) => {
      snap.forEach((child) => {
        diaries.push({
          key: child.key,
          name: child.val().name,
          date: child.val().description,
          url: child.val().url,
          idOwner: child.val().idOwner
        });
      });
      console.log(diaries.length); // get 0
      resolve(diaries);
    });
  });
}