首页 > 解决方案 > 如何在 Firestore 中调用 Async 和 Await

问题描述

我有一个从 firestore db 获取数据的功能。

PlayerService.js

 //...
 async getHighestPlayers(game){
    const snapshot = await this.db
    .collection(game)
    .orderBy("score","asc")
    .limitToLast(1)
    .get();

    // What should I need to return ?

    snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
      });
  }  

index.js

router.get('/', function(req, res, next) {
  const  highestPlayers = playerService.getHighestPlayers("game1"); 
  res.render('index', { highestPlayers: highestPlayers});
});

如何进行async getHighestPlayers(game)return ,以便我可以调用并使用它来显示结果?

标签: node.jsexpressgoogle-cloud-firestore

解决方案


您需要添加 async-await 以等待getHighestPlayers完成执行index.js

router.get('/', async function(req, res, next) {
  const  highestPlayers = await playerService.getHighestPlayers("game1"); 
  res.render('index', { highestPlayers: highestPlayers});
});

改变在getHighestPlayers

async getHighestPlayers(game){
    const snapshot = await this.db
    .collection(game)
    .orderBy("score","asc")
    .limitToLast(1)
    .get();

    return snapshot;
  }   

推荐阅读