简体   繁体   English

创建一个返回承诺并处理回调的函数

[英]Creating a function that returns a promise and handle the callback

Here is my code: 这是我的代码:

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

When I log the users in the first then I get 当我登录的用户在第一然后我得到

[ [Function], [Function], [Function], [Function] ] [[功能],[功能],[功能],[功能]]

and it gets triggered before the users are retrieved from the firebase. 并且会在从Firebase检索用户之前触发它。 So if I console.log(user) in the getUserRatingsSorted function they get printed after the users are logged. 因此,如果我在getUserRatingsSorted函数中console.log(user) ,则在用户登录后将其打印出来。 For me this doesn't sound right since things in the promise should be printed then things in the then . 对我来说,这听起来并不正确,因为事情的承诺应印有那么事情在当时 I believe I am doing something wrong in creating a promise function. 我相信我在创建Promise函数时做错了。

on() doesn't return a promise (as you can see from the linked API docs). on()不会返回承诺(如从链接的API文档中可以看到的)。 It listens indefinitely, until you remove the listener. 它会无限期地监听,直到您删除监听器为止。 Instead, use once() to perform a single query that returns a promise to indicate that the query is complete, containing a snapshot of the data. 而是,使用一次()执行单个查询,该查询返回一个承诺以表示查询已完成,其中包含数据快照。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM