【问题标题】:Underscore and Mongoose: Use document as outer function's return value下划线和猫鼬:使用文档作为外部函数的返回值
【发布时间】:2011-12-19 05:04:06
【问题描述】:

我正在尝试同时使用 Mongoose 和 Underscore 来做这样的事情:

var person_ids = [1, 2, 3];

var persons = _(person_ids).map(function(id) {
    Person.findById(id, function(person) { // Non-blocking
        // How do I use 'person' as the outer function's return value?
    });
});

有没有办法做到这一点?我意识到我可能试图在设计为异步使用的库上强制使用同步范例。

【问题讨论】:

  • 不知道 findById 是异步的。看起来你被困在一个扭曲的回调迷宫中。不过试试Person.find 方法。

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


【解决方案1】:

获得价值的唯一方法是通过回调:

检查我的答案: How to retrieve value of a variable in class

代码中重要的地方是:

Place.getActualId(function(id){ console.log(id); });

 getActualId: function(callback){
       this.find({where: {actual: 1}}).on('success', function(placeTmp){
       callback(placeTmp['id']);
 })

【讨论】:

  • 是的,这就是我对 Mongoose 库工作原理的理解。但是,发现它与 Underscore 提供的功能完全不兼容,令人失望。
猜你喜欢
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
  • 2016-11-04
  • 2015-01-06
  • 2020-04-26
  • 1970-01-01
相关资源
最近更新 更多