Javascript 将元素推入异步/等待函数内的数组中
我有一个Javascript 将元素推入异步/等待函数内的数组中,javascript,node.js,express,google-cloud-firestore,async-await,Javascript,Node.js,Express,Google Cloud Firestore,Async Await,我有一个PlayerService.js使用 expressjs和firestore作为数据库: PlayerService.js 当我放置console.log({key:player.name,value:doc.data()})时,显示预期的输出 但是当我打印console.log(toptenPlayers)时,它返回了[] 我对将阵列推入wait/async函数的误解是什么?使用此npm包而不是forEach: async getUserProfile(uid){ const
PlayerService.js
使用
expressjs
和firestore
作为数据库:
PlayerService.js
当我放置console.log({key:player.name,value:doc.data()})时,
显示预期的输出
但是当我打印console.log(toptenPlayers)
时,它返回了[]
我对将阵列推入wait/async函数的误解是什么?使用此npm包而不是forEach:
async getUserProfile(uid){
const userRef = this.db.collection('users').doc(uid)
const doc = await userRef.get();
return doc.data();
}
async getToptenPlayers(game){
const toptenPlayers = [];
const snapshot = await this.db
.collection(game)
.orderBy("score","desc")
.limitToLast(10)
.get();
snapshot.forEach(async doc => {
//console.log(doc.id, '=>', doc.data());
const player = await this.getUserProfile(doc.id);
//1. console.log({ key: player.name, value: doc.data() })
toptenPlayers.push({ key: player.name, value: doc.data() });
});
//2. console.log(toptenPlayers)
return toptenPlayers;
}