【问题标题】:How can I use the results of this promise?我如何使用这个承诺的结果?
【发布时间】:2017-06-25 04:36:36
【问题描述】:

我正在尝试为我的社交帖子提要构建 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;
};

如果interestmyInterests 出现,那么我想查找属于用户(userId)的interests 数组。

每个帖子都有一系列类别:query.categories

一旦我得到interests 数组,我想查找query.categories,以过滤到用户对myInterests 感兴趣的帖子。

现在,我的测试表明这只是被忽略了。它带回了所有的帖子。我在这里做错了什么?

谢谢

【问题讨论】:

  • User.findById 是异步的。该函数在执行 User.findById 查询之前返回。尝试承诺或回调。
  • 这是控制台日志user.interests 如果我把它放在 then 语句中?

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您需要等待结果,为此您的函数需要为更新的查询返回另一个承诺。

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

然后在执行查询之前等待这个promise:

buildQuery(criteria).then(runQuery).then(results => … )

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 2017-04-30
    • 2021-06-29
    • 2017-08-14
    • 1970-01-01
    • 2013-12-08
    • 2022-11-22
    • 2019-12-21
    • 1970-01-01
    相关资源
    最近更新 更多