1

I'm trying to get the length of my array, but I always getting 0 even when the console show that I push 5 objets

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)
})}

This is what the console shows me enter image description here

KENdi
  • 7,576
  • 2
  • 16
  • 31

3 Answers3

1

Move the console.log into your callback function, otherwise it will mostly always run before your callback is executed. In other words: you get a 0 because the length is 0 at this point.

Rob
  • 11,492
  • 14
  • 59
  • 94
1

Ofcourse you will get this 0 because this is async function you can try like that

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);
});
})}
Sourabh Somani
  • 2,138
  • 1
  • 13
  • 27
1

url.on is likely asynchronous, meaning you need to do the console.log inside the callback:

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);
    });
  });
}
Austin Greco
  • 32,997
  • 6
  • 55
  • 59