node.js - 如何在 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 ,以便我可以调用并使用它来显示结果?
解决方案
您需要添加 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;
}
推荐阅读
- mongodb - 错误:子进程中发生异常:ChecksumMismatchError: SHA256 mismatch
- javascript - 当有函数不使用'yield'或'call'或'put'之类的效果时,如何测试sagas?
- c - 来自指针的函数中的指针:声明不兼容
- if-statement - 有没有办法计算空白单元格,但前提是它们在具有值的单元格之间,在 Google 表格中?
- python - 如何根据需要将多个 csv 文件与 Python 合并?
- python - 如何在没有用户名/密码系统的 Django 中进行会话?
- azure - 为什么在 Azure DevOps 中部署时收到“InternalServerError”?
- python - 是否可以使用 Jupyter Notebooks 禁用/隐藏 gmap 中的控件?
- kdb - 如何从带有 kdb+/q 列表的表中选择列的子集?
- javascript - Javascript将长字符串编码为csv失败