2017-07-24 141 views
1

我試圖讓我的數組的長度,但我總是得到0,即使控制檯顯示,我把5個OBJETSArray.length等於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

+1

在您的數組被填充之前正在打印...您在異步概念中誤導 – guijob

回答

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); 
    }); 
    }); 
} 
+0

非常感謝! ,我不是控制異步功能的主人,很難獲得核心思想 –

1

將console.log移動到您的回調函數中,否則在執行回調之前,它通常會運行。換句話說:你得到一個0,因爲此時的長度 0。

1

Ofcourse,你會得到這個,因爲這是異步功能,你可以嘗試這樣的

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