gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:10:49 24 4
gpt4 key购买 nike

这是我的代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com