【问题标题】:Having trouble trying to execute find with MongoDB in node.js asynchronously尝试在 node.js 中使用 MongoDB 异步执行 find 时遇到问题
【发布时间】:2013-03-08 09:49:28
【问题描述】:

我正在从我的路由中获取一个请求参数,例如mydomain.com/topic/animals 其中requestParam = req.params.topicName 在这种情况下为animals

我遍历一个包含所有可能主题的对象,然后如果找到与 requestParam 匹配的 topicName,然后我想执行对数据库的调用以返回该主题的所有集合。

问题在于它是同步执行的,因为它总是会执行 else 子句,例如

if (requestParam === topicName) {
  // fetch submission
} else {
  // return 404
}

所以它总是返回 404,但如果我在这里去掉 else 子句,它就会起作用。我查看了下划线的_.after(),但无法使其正常工作(甚至不确定这是否是我应该使用的?

我的代码:

_.each(topics, function(key, topic) {
  var topicName = key['topicName'],

  if (requestParam === topicName) {
    Submission.getTopicSubmissions({ topicName : topicName }, function(err, submissions) {
      if (err) {
        res.redirect('/');
      } else if (submissions) {
        res.render('topic', {
          submissions: submissions
        });
      } else {
        res.redirect('/topics');
      }
    });
  } else {
    res.render('errors/404', {
      title: 'Page Not Found -',
      status: 404,
      url: req.url
    });
  }
});

【问题讨论】:

    标签: javascript node.js mongodb asynchronous underscore.js


    【解决方案1】:

    问题是您不应该在每次迭代中渲染 404。因为您进行异步查找,所以它计划在未来某个时间点执行,同时当前函数继续运行。毫无疑问,您将在某个时候遇到不同的情况并至少渲染一次 404。使用可破坏的迭代,搜索时标记,并在迭代之外执行 404,如下所示:

    var isWaitingForResult = false;
    topics.every(function(topic, key) { // TODO: Check if this iterator matches _.each
        var topicName = key['topicName'],
    
        if (requestParam === topicName) {
          isWaitingForResult = true; // Wait for the result.
          Submission.getTopicSubmissions({ topicName : topicName }, function(err, submissions) {
            if (err) {
              res.redirect('/');
            } else if (submissions) {
              res.render('topic', {
                submissions: submissions
              });
            } else {
              res.redirect('/topics');
            }
          });
          return false; // stop iteration, we did start our search after all
        }
        return true; // continue iteration so we have another chance.
    });
    if (!isWaitingForResult) { // did a search NOT start?
        res.render('errors/404', {
          title: 'Page Not Found -',
          status: 404,
          url: req.url
        });
    }
    

    请注意,我不确定我是否正确地重写了每一个。检查这个。 :)

    【讨论】:

    • 啊哈...好吧,这需要一些时间来适应,但我现在终于可以摸索了。顺便说一句,这完全有效。谢谢! :D
    猜你喜欢
    • 2021-07-14
    • 2018-08-21
    • 2019-11-05
    • 2018-02-08
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多