[英]How can I use the results of this promise?
I'm trying to build a buildQuery
function for my social post feed:我正在尝试为我的社交帖子提要构建一个
buildQuery
函数:
const buildQuery = (criteria) => {
const { userId, interest } = criteria;
const query = {};
if (interest !== 'everything') {
if (interest === 'myInterests') {
User.findById(userId).then(user => {
return query.categories = {
$in: user.interests
};
});
} else {
query.categories = { $eq: interest };
}
}
return query;
};
If interest
comes through as myInterests
then I want to go find the array of interests
belonging to the user ( userId
).如果
interest
作为myInterests
那么我想去查找属于用户的interests
数组 ( userId
)。
Each post has an array of categories: query.categories
.每个帖子都有一组类别:
query.categories
。
Once I get back the interests
array, I want to look up query.categories
, to filter down to the posts that the user is interested in myInterests
.一旦我取回
interests
数组,我想查找query.categories
,以过滤到用户对myInterests
感兴趣的myInterests
。
Right now, my test is showing that this is just being ignored.现在,我的测试表明这只是被忽略了。 It's bringing back all the posts.
它正在带回所有帖子。 What am I doing wrong here?
我在这里做错了什么?
Thank you谢谢
You will need to wait for the results, and for that your function needs to return another promise for the updated query.您将需要等待结果,为此您的函数需要为更新的查询返回另一个承诺。
function buildQuery({userId, interest}) {
if (interest === 'everything')
return Promise.resolve({});
else
return (interest === 'myInterests'
? User.findById(userId).then(user => ({$in: user.interests}))
: Promise.resolve({$eq: interest})
).then(categories => ({categories}));
}
Then wait for this promise before executing the query:然后在执行查询之前等待这个承诺:
buildQuery(criteria).then(runQuery).then(results => … )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.