2013-03-08 69 views
0

我从我的路由中获取请求参数例如mydomain.com/topic/animals其中requestParam = req.params.topicName,在这种情况下,animals。通过包含所有可能的话题对象尝试异步执行在node.js中使用MongoDB查找时遇到问题

我循环,然后如果我找到相匹配的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 
    }); 
    } 
}); 

回答

0

的问题是,你不应该渲染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 
    }); 
} 

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

+0

啊哈......好吧,这需要一些习惯,但我现在终于可以开始了。这完全工作,顺便说一句。谢谢! :d – 2013-03-08 11:20:50

相关问题