javascript - 创建一个返回 Promise 并处理回调的函数

标签 javascript firebase firebase-realtime-database promise

这是我的代码:

function getUserRatingsSorted(userIds) {
  return Promise.all(userIds.map(id => {
    return admin.database().ref().child('users').child(id).on('value', (s) => {
      const user = s.val();
      user.id = id;
      return user;
    });
  }));
}
function prepareGameForStart(userIds) {
  getUserRatingsSorted(userIds)
  .then((users) => evaluateUsersByRatings(users))
  .then((playerAndRatings) => distributePlayersInTeams(playerAndRatings))
  .then(notification.sendPushNotificationTo('Teams have been selected', 'Log in to your group to see your team', userIds))
  .catch((error) => {
    console.log(error);
  });
}

当我在第一个然后中记录用户时,我得到

[ [Function], [Function], [Function], [Function] ]

它会在从 Firebase 检索用户之前触发。因此,如果我在 getUserRatingsSorted 函数中 console.log(user),它们会在记录用户后打印出来。对我来说,这听起来不太正确,因为 Promise 中的内容应该然后 then 中的内容打印。我相信我在创建 promise 函数时做错了。

最佳答案

on()不返回 promise (正如您可以从链接的 API 文档中看到的那样)。它会无限期地监听,直到您删除监听器。相反,使用 once()执行单个查询,该查询返回一个 promise 以指示查询已完成,其中包含数据快照。

关于javascript - 创建一个返回 Promise 并处理回调的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52216598/

相关文章:

ios - Firebase 性能 |控制台中没有数据出现

javascript - 构造函数不工作?

javascript - 从值数组中计算不同的 MongoDb

java - 如何在 RecyclerView Item 的 populateViewHolder 中设置 addSnapshotListener 和 remove?

java - Firebase 数据库查询结合 orderByChild 和 startAt 不返回任何内容

ios - 在 Firebase iOS SDK 中更新实时数据库对象

swift - Firebase 在 TableView 中检索和插入

javascript - 在 CkEditor 中,如何在当前编辑时应用样式表?

javascript - Umbraco网站如何使用razor实现分页搜索

angular - 错误 : Cannot find module "angularfire2/database-deprecated" appmodule ionic 3, Angularfire2