gpt4 book ai didi

javascript - 在这种情况下如何返回 promise ?

转载 作者:行者123 更新时间:2023-12-03 02:50:11 24 4
gpt4 key购买 nike

我是使用 JavaScript 的 Firebase 新手,我知道我可以使用检索到的数据的输出返回一个 Promise。但在以下情况下我无法真正看清它:

filterUsersAndCalculateMatches = (userProfile, userID, potentialMatches, maxDistanceToSearchForMatches) => {
const TOTAL_SCORE = 100;
var matches = {}; // Matches to be stored in the database
potentialMatches.forEach(user => {
if (user.val() !== userID) {

databaseRef.child(`users/${user.val()}/profile`).once("value", (snapshot) => {
const matchScore = calculateMatchScore(userProfile, snapshot.val(), maxDistanceToSearchForMatches);
//console.log("final score is " + matchScore);
if (matchScore) {
const match = {
compatibility: matchScore / TOTAL_SCORE,
distance: distance,
profile: snapshot.val()
}
matches[user.val()] = match;
}
});
}
});
};

我正在迭代用户的 ID 并访问他们的个人资料以进行一些计算,并将结果与​​他们的个人资料一起添加到对象中。

在所有用户都完成后,如何返回匹配对象的 promise ?

最佳答案

.once()返回一个 promise 。您可以使用Promise.all() 。 Promise.all() 获取一个 Promise 数组作为参数,并返回一个 Promise,当所有传递的 Promise 解析时它将解析。修改后的代码如下所示:

filterUsersAndCalculateMatches = (userProfile, userID, potentialMatches, maxDistanceToSearchForMatches) => {
var matches = {}; // Matches to be stored in the database
const promisesList = [];
potentialMatches.forEach(user => {
if (user.val() !== userID) {
// save a reference to the promise
const dataPromise = databaseRef.child(`users/${user.val()}/profile`).once("value", (snapshot) => {
// ...
});
// push the promise in the promise list
promiseList.push(dataPromise);
}
});

return Promise.all(promisesList).then(() => Promise.resolve(matches));
};

即使列表中的某个 promise 被拒绝,您也可能想要解决。您可以执行以下操作,处理拒绝的 promise 。

promiseList.push(
// have to handle the reject
dataPromise
.then(data => data)
// returns a resolved promise with { error } object.
// doing this Promise.all() will always resolve even if some of them are rejected.
.catch(error => {
return { error: error };
})
);

关于javascript - 在这种情况下如何返回 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47902705/

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