简体   繁体   中英

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. So if I console.log(user) in the getUserRatingsSorted function they get printed after the users are logged. 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.

on() doesn't return a promise (as you can see from the linked API docs). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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